Learn How To Exception Handling in C#

Development
Jan 03, 2023
6 Mins Read
Learn How To Exception Handling in C#

The exception-handling procedure in C# is used to handle runtime problems. We create exceptions to allow runtime errors to not disrupt the application’s normal operation.

In C#, an exception is an object or event that is thrown during runtime. All deviations originate from the System. unique case category. It is a runtime error, so it is fixable. If we ignore the exception, the program will crash and print an error message.

Because exception management tactfully handles an unwanted event, an exception, and the user can still comprehend the program code, exception handling is crucial.

Exception Classes in C#

The System. The exception class is the root of all exception classes in C#. Here is a list of the standard exception classes in C#.

Exception Class & Description:
1. System.IO.IOException

Error handling for I/O.

2. System.IndexOutOfRangeException

Handles the errors produced when a method uses an out-of-range array index.

3. System.ArrayTypeMismatchException

Handles errors produced when the type of an array is incorrect.

4. System.NullReferenceException

Handles referring to null object-related problems.

5. System.DivideByZeroException

Handles blunders caused by dividing a payout by zero.

6. System.InvalidCastException

Corrects mistakes made during typecasting.

7. System.OutOfMemoryException

Handles failures caused by a lack of available memory.

8. System.StackOverflowException

Deals with issues caused by stack overflow.

Dealing with Exceptions

Try and catch blocks, a structured approach to exception management, are provided by C#. These blocks are used to separate the main programme statements from the error-handling statements.

The try, catch, finally and throw keywords are used to implement these error handling blocks.

Try:

The try keyword creates a block in which we must write the statements that cause the exception and their related ideas. 

Therefore, the try block must contain the exception-causing instructions and any associated statements that should not be executed when an exception occurs. 

The CLR will generate an instance of the Exception class based on the logical error when an exception occurs, and it will then throw that instance, which the relevant catch block will handle.

Catch:

The catch block catches the exception thrown from the try block’s equivalent catch block. It has the logic to deal with the caught exception by taking the appropriate action. In C#, the syntax of a Catch block resembles a function Object() { [native code] }. 

It does not accept return types, regular modifiers, or accessibility modifiers. It only takes a single parameter of type Exception or any of the parent Exception class’s subclasses. Any permissible statement in .NET can be written inside the catch block, including statements that raise exceptions. 

In this situation, we can halt the program’s abnormal termination and provide the user with an intelligible error notice so they can take the appropriate step to fix the problem.

Finally:

Creating a block by the keyword finally ensures that all statements within it are executed without fail, regardless of whether an exception has happened. 

In other words, whether an exception is thrown or not, whether the catch block handles the thrown exception or not, the statements placed in the final block will always be performed.

Syntax

If a block throws an exception, a method can catch it by combining the try and capture keywords. 

A try/catch block wraps the code that might cause an exception. Use of try/catch requires the following syntax.

try {

   // statements causing exception

} catch( ExceptionName1 ) {

   // error handling code

} catch( ExceptionName2 ) {

   // error handling code

In the preceding example, a try block was used to enclose this code. The software will go to the catch block if an exception occurs inside a try block. We show the user a message explaining his error inside a catch block, and we offer the user a statement explaining what to do after running a program inside a finally block.

Throw

An exception is raised by software when a problem occurs. A throw keyword is used to do this.

} catch( ExceptionName3 ) {

   // error handling code

} finally {

   // statements to be executed

}

Syntax

 try

    {

          // statements causing exception

    }

    catch(ExceptionName1)

    {

        throw;

    }

Final Words

Control will move to the outer catch block until an appropriate exception filter is found if there isn’t an inner catch block that matches the raised exception type.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts