Home >Backend Development >C#.Net Tutorial >Exception Handling in C#
We can not expect a user to enter the correct details all the time. However, if the incorrect or unexpected input is not handled correctly, the entire code could crash or go with an endless loop. This is a problem that starts while executing the program due to unexpected conditions or inputs. For example, the result is infinite when a number is being divided by zero. Exception handling is the way to tell the program to move on to the next block of code or provide the defined result in certain situations.
Exception handling could be done with below four keywords.
You may save the software or your code from a lot of hassle by defining the exception handler. It’s a good practice to define exception handler wherever there is a possible exception.
Syntax:
Whenever the exception is raised, a declared method catches the exception with the help of try and catch keyword. We need to place this combination on the part of the code, an exception is expected. These codes are called protected code. You can also define more than one catch keyword for one try keyword. At the end of the content, the final part of the code will be executed to and that will be executed whether or not an exception is raised.
Code:
try { //Define the statement that could cause an exception. } Catch(ExceptionName secondException) { //error handling code } Finally { //define the statement that will be executed }
There are many predefined classes for handling the exception. The try block covers the part of the code which might throw an exception and catch confirms what to do when an exception is caught. The final part of the block defines what must be done whether or not the exception is detected and the throw part displays the message if set any.
There are many classes available in C# through which exceptions can be represented. All the classes are derived from the main class called System. Exception. There are few classes which are also derived from System.ApplicationException and System.SystemException.
Exceptions are derived from System. Exception class. Here is the list of C# common exception classes.
|
Description | ||||||||||||
System.DivideByZeroException | handles the error when trying to divide a number by zero. | ||||||||||||
System.NullReferenceException | handles the error when referring to an object which does not exist. | ||||||||||||
System.InvalidCastException | handles the error when trying invalid casting. | ||||||||||||
System.IO.IOException | All input-output error is handled. | ||||||||||||
System.FieldAccessException | When trying to access unauthorized class |
Exception handling is done by try and catches block in C#. The try block in C# is used to place the code that may throw an exception. The exception is handled by the catch block.
Code:
using System; public class exceptionhandling { public static void Main(string[] args) { int a = 10; int b = 0; int x = a/b; //we are trying to divide the number with zero Console.WriteLine("other part of the code"); } }
Output:
Code
using System; public class ExExample { public static void Main(string[] args) { try { int a = 10; int b = 0; int x = a / b; } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Rest of the code"); } }
Output:
It will show you the message regardless the exception is caught.
Code
using System; public class Exceptionhandling { public static void Main(string[] args) { try { int x = 5; int y= 0; int z = x / y; } catch (Exception obj) { Console.WriteLine(obj); } finally { Console.WriteLine("Time to execute finally block"); } Console.WriteLine("Other part of the code"); } }
Output:
Code
using System; public class ExceptionHandling { public static void Main(string[] args) { try { int p = 6; int q = 0; int r= p/q; } catch (NullReferenceException nullObject) { Console.WriteLine(nullObject); } finally { Console.WriteLine("Exception not handled. Now Finally section will be executed"); } Console.WriteLine("Other part of the code"); } }
Output:
The not only system defined, but we can also set our own exception. However, we need to inherit the code in order to get this done.
Code
using System; public class userdefinedInvalidAge : Exception { public userdefinedInvalidAge (String errorMessage) : base(errorMessage) { } } public class TestUserDefinedException { static void validateAge(int age) { if (age < 18) { throw new userdefinedInvalidAge("Sorry, Age must be greater than 18"); } } public static void Main(string[] args) { try { validateAge(12); } catch (userdefinedInvalidAge e) { Console.WriteLine(e); } Console.WriteLine("Rest of the code"); } }
Output:
At any place you think it might generate an error because of anything, exception handler should be used. It is essential that you use a catch statement and start from generic to a specific exception. Your entire software or code is at risk without proper exception handler.
The above is the detailed content of Exception Handling in C#. For more information, please follow other related articles on the PHP Chinese website!