Exception handling is the concept where there are lots of methodology defined to handle the exception or we can say error. It can be run time exception or compile time exception.
Basically exception or error is point to faults which can be occurred during the program execution or program development. If you don’t handle the exception, then it makes program faulty or give the wrong result.
There are many types of errors in C#. It can be syntax error or logical error.
Syntax Errors
When you make some typing mistake like you are writing the program and instead of writing, if you write IF then it will be a syntax error since C# is a case sensitive language.
- int myvalue = 10;
-
- IF(myvalue > 10)
- {
-
- }
Runtime Errors Runtime errors occur during execution of the program that is why we also called runtime exceptions. If you does not create logic in proper way, then it create runtime exception.
- int a = 10, b = 0;
-
- var c = a / b;
How to handle error or exception Using exception handling, we can handle exception in a proper way and show the accurate result as per user understanding. It is a mechanism to detect and handle run time errors. We can achieve this using Try-Catch-Finally blocks.
Try block In the try block, you need to put those codes which can be created exception. The try block encloses the statements that supposed to be throwing an exception.
- int a = 10, b = 0;
- try
- {
- var c = a / b;
- }
Catch block If any exception comes on the time of program execution that Catch block handles any exception if one exists.
Finally block If you think that some logic is necessary to execute in any condition, then it need to put in the finally block. It can be used for doing any clean-up process like releasing unused resources even if an exception is thrown.
Full example of try-catch-finally: - using System;
- namespace ExceptionHandling
- {
- class MyClass
- {
- int result;
- MyClass()
- {
- result = 0;
- }
- public void division(int num1, int num2)
- {
- try
- {
- result = num1 / num2;
- }
- catch (DivideByZeroException e)
- {
- Console.WriteLine("Exception caught: {0}", e);
- }
- finally
- {
- Console.WriteLine("Result: {0}", result);
- }
- }
- static void Main(string[] args)
- {
- MyClass d = new MyClass();
- d.division(25, 0);
- Console.ReadKey();
- }
- }
- }
Key points about exceptions handling:
- Exceptions are types that all directly or indirectly derive from System.Exception class.
- A try block is used to throw multiple exceptions that can handle by using multiple catch blocks.
- The statements inside the finally block are always executed whether exception occurs or not in the program.
- The order of try-catch-finally is like this try-catch-catch….-finally.
So, finally you learned what is exception handling and how can we handle exceptions in C#.