Creating custom exceptions


This article explains about how Exceptions are very use full while developing high level applications as well as how to create a custom exceptions.

Exceptions are very use full while developing high level applications; normally we are using the try catch block to catch the exceptions thrown by the .net frame work. As the same way we can create/handle our own exceptions.

Rule: All types of exceptions must derive from “System.Exception" class.

Here's the simple example. I have created a exception class named “InvalidUserException" which I am invoking when the current user is not valid to access the application.


Creating custom exception, by inheriting the “System.Exception"


//Creating own exception by inheriting the Exception class
public class InvalidUserException:Exception
{
public override string Message
{
get
{
return "Invalid User";
}
}
}


Implementing the “LoginManager" class, which is used to validate the current user

public class LoginManager
{
//Instead of hard coded values you can add logic to retrive from the database
public string ValidUserName="Admin";
public string ValidPassword="AdminPass";

public bool ValidateUser(string userName,string password)
{
if (ValidUserName == userName && ValidPassword == password)
{
//Login successful
return true;
}
{
//Login Failed
throw new InvalidUserException();
}
}
}




Testing the implementation

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}



private void Form1_Load(object sender, EventArgs e)
{
LoginManager lm = new LoginManager();

string currentLoginName = textBox1.Text;
string currentLoginPassword = textBox2.Text;
try
{
if (lm.ValidateUser(currentLoginName, currentLoginPassword))
{
//User is valid,Open next form
MessageBox.Show("Login Success");
}
}
//Catching the custom exception
catch (InvalidUserException ex)
{
MessageBox.Show(ex.Message, "Login Faild", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

//Resets the input elements
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
}


}


}


Comments

Guest Author: Jayesh Sorathia19 Nov 2012

There is a situations where you need to create and handle a custom exception for handling runtime's exception for application-specific exceptions.
Read this article in this article code is given in both C#.Net Example and VB.Net Example and also downloadable code.
Link : http://jayeshsorathia.blogspot.com/2012/10/create-and-handle-custom-exception-in-net.html



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: