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; }
}
}
|
No responses found. Be the first to respond and make money from revenue sharing program.
|