Creating custom exceptions

Creating 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 own exception by inheriting the Exception class
public class InvalidUserException:Exception
{
public override string Message
{
get
{
return "Invalid 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();
}
}
}



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

No responses found. Be the first to comment...


  • 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: