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:
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.
Try with Multiple Catch Blocks: One try block can have multiple catch blocks to handle different types of exceptions occur in different lines of code. Program to read 2 numbers and perform division: In this program, we need to handle two exceptions We can handle Multiple exceptions in following ways: Try with Multiple Catch blocks: …
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.
Finally block: Why closing statements belongs to finally block? Open and close the file using finally block:
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: