Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:10
Show Gist options
  • Save dnasca/c25c84523076abc97e93 to your computer and use it in GitHub Desktop.
Save dnasca/c25c84523076abc97e93 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
/* Custom Exception Notes
*
* End the custom exception class name with 'Exception'. All .NET exceptions end with the 'Exception' suffix. eg. UserAlreadyLoggedInException
*
* If you want to provide the capability to use innerExceptions, you must overload the constructor as seen below.
*
* If you want your Exception class object to work across application domains, then the object must be serializable. To make your exception class serializable, mark
* it with the [Serializable] attribute and provide a constructor that invokes the base Exception class constructor that takes in SerializationInfo and StreamingContext
* objects as parameters
*
* Program Requirements (to demonstrate creating a custom Exception class)
* 1. The application should allow the user to have only one logged in session
* 2. If the user is already logged in, and the user opens another browser window to try to log in again
* the application should throw an error stating that he/she is already logged in, in another browser window/tab
*
*/
class Program
{
public static void Main()
{
try
{
throw new UserAlreadyLoggedInException("You are already logged in.");
}
catch (UserAlreadyLoggedInException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
[Serializable]
public class UserAlreadyLoggedInException : Exception
{
public UserAlreadyLoggedInException() //parameterless constructor, inheriting from Exception base class
: base()
{
}
public UserAlreadyLoggedInException(string message) //method overload that accepts a string
: base(message)
{
}
public UserAlreadyLoggedInException(string message, Exception innerException) //method overload that can accept a string and track an inner exception
: base(message, innerException)
{
}
public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context) //constructor that supports base class serialization
: base(info, context)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment