Home >Backend Development >C#.Net Tutorial >Exception Handling in C#

Exception Handling in C#

WBOY
WBOYOriginal
2024-09-03 15:20:231118browse

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.

Keywords of Exception Handling in C#

Exception handling could be done with below four keywords.

  1. Try: The try block defines the type of exception to be handled. This is where the exception would be caught. It will always pair up with one catch block.
  2. Catch: Once the try block has defined the type and got one exception during the execution, the catch block will confirm the type of exception handler to be used. This block will also determine where the exception is to be handled. As the keyword indicates, it is like catching the exception.
  3. Finally: This block has some set of statements. Regardless of the exception is thrown, the statements defined in the final block will always be executed.
  4. Throw: When an exception is caught, throw keyword is used to show the caught exception.

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
}

How Does Exception Handling work in C#?

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.

Exception Classes in C#

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.

Examples of Exception Classes in C#

Exceptions are derived from System. Exception class. Here is the list of C# common exception classes.

                   Exception                    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
                   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

1. C# try/catch

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.

C# example without try/catch

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:
Exception Handling in C#

C# try/catch example

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:
Exception Handling in C#

Use of Exception Classes in C# finally

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:
Exception Handling in C#

1. C# finally example if Exception is not handled

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:
Exception Handling in C#

2. C# user-defined Exception

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:
Exception Handling in C#

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Entity Framework C#Next article:Entity Framework C#