C# Exceptions

C# – Introduction to Exceptions

Introduction: While compiling and executing the code, chance of getting different types of errors. Logical Errors: If we get the output of code instead of Expected contains Logical error. FormatException: It occurs if user enter invalid input while reading through ReadLine(). Output:

C# – Handling Exception – Try – Catch

Handling Exception using try-catch: try block: catch block: Handling FormatException: Note : Catch block executes only if exception raises in try block. IndexOutOfRangeException: Index was outside the bounds of the array. DivideByZeroException: Attempted to divide by zero NullReferenceException: Object reference not set to an instance of an object.

C# – Handling Multiple Exceptions

Handling multiple exceptions with more than one catch block: Handling multiple exceptions with single catch block: Handling exceptions with Logical OR(||) operator: Note: It is not possible to handle child type exception after handling parent type exception as shown below.

C# Custom Exceptions

Custom Exceptions: You can create custom exceptions by creating a new class that derives from the System.Exception class In this example, MyCustomException is a class that derives from the Exception class. It has three constructors that take different parameters: Throw keyword: You can catch this exception using a try-catch block and handle it accordingly:

Scroll to Top