1. What is Exception
-
Exception: An error that occurs during the execution of a program.
-
Exceptions disrupt the normal flow of the program.
-
They are objects derived from the
System.Exceptionbase class. -
Examples: Division by zero, invalid file access, null reference.
2. Rules for Handling Exception
-
Every exception in C# is an object of a class derived from
System.Exception. -
Code that may cause an exception should be placed inside a
tryblock. -
One or more
catchblocks can handle exceptions. -
The
finallyblock (if used) always executes, whether an exception occurs or not. -
If an exception is not handled, the runtime will terminate the program.
-
Specific exceptions should be caught before general exceptions.
3. Exception Classes and Its Important Properties
-
Base class:
System.Exception -
Important Properties:
-
Message→ Description of the error. -
StackTrace→ String representation of the call stack. -
InnerException→ Gets the original exception if wrapped. -
HelpLink→ Link to a help file related to the error. -
Source→ Name of the application/object that caused the error. -
TargetSite→ Method where the exception was thrown.
-
Common Exception Classes:
-
DivideByZeroException -
NullReferenceException -
IndexOutOfRangeException -
FileNotFoundException -
InvalidCastException
4. Understanding & Using try, catch keyword
-
try block → contains code that might throw an exception.
-
catch block → handles the exception.
Example:
try
{
int a = 10, b = 0;
int c = a / b; // Will throw DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}5. Throwing Exceptions, Importance of finally Block
- throw keyword → Used to explicitly throw an exception.
Example:
throw new InvalidOperationException("Invalid operation performed.");-
finally block:
-
Always executes (even if exception occurs).
-
Used for cleanup activities like closing files, releasing database connections, etc.
-
Example:
try
{
// risky code
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Cleanup code executed.");
}6. Writing Custom Exception Classes
-
You can create custom exceptions by inheriting from
System.Exception. -
Useful for application-specific error handling.
Example:
public class AgeException : Exception
{
public AgeException(string message) : base(message) { }
}
class Program
{
static void Main()
{
int age = 15;
try
{
if (age < 18)
throw new AgeException("Age must be 18 or above.");
}
catch (AgeException ex)
{
Console.WriteLine("Custom Exception: " + ex.Message);
}
}
}