how to handle a exception in c# code example
Example 1: exception handling c#
try {
} catch( ExceptionName e1 ) {
} catch( ExceptionName e2 ) {
} catch( ExceptionName eN ) {
} finally {
}
Example 2: c# creating exceptions
class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
}
[Serializable]
class InvalidStudentNameException : Exception
{
public InvalidStudentNameException()
{
}
public InvalidStudentNameException(string name)
: base(String.Format("Invalid Student Name: {0}", name))
{
}
}
class Program
{
static void Main(string[] args)
{
Student newStudent = null;
try
{
newStudent = new Student();
newStudent.StudentName = "James007";
ValidateStudent(newStudent);
}
catch(InvalidStudentNameException ex)
{
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
private static void ValidateStudent(Student std)
{
Regex regex = new Regex("^[a-zA-Z]+$");
if (!regex.IsMatch(std.StudentName))
throw new InvalidStudentNameException(std.StudentName);
}
}