Exception handling in C# – In this article, we will learn, what is an exception, what the different types of exceptions are, How to handle exceptions, and how to create a custom exception.
What is Exception?
Exception is an error or unwanted result in the application. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors.
There are 2 main types of Exception:
Compile Time Exceptions:
Compile-time exceptions occur due to syntax errors or incorrect syntax codes. These errors can be found at compile time. These errors are easy to find.
Runtime Exceptions:
Runtime exceptions occur at the time of the actual execution of an application. These exceptions occur due to logical errors such as attempting a number to divide by 0 and so on. These exceptions are difficult to predict or find out. But we can control these errors to some extend.
The exception handling features in C# language helps you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling in C# uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. Exceptions are created by using the throw
keyword.
In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. When this happens, the CLR will unwind the stack, looking for a method with a catch
block for the specific exception type, and it will execute the first such catch
block that if finds. If it finds no appropriate catch
block anywhere in the call stack, it will terminate the process and display a message to the user.
Note: The Exception class is a base class for all exceptions.
Common Exceptions
The following table lists some common exceptions with examples of what can cause them.
Exception type | Base Type | Description | Example |
Exception | Object | Base class for all exceptions. | None (use a derived class of this exception). |
IndexOutOfRangeException | Exception | Thrown by the runtime only when an array is indexed improperly. | Indexing an array outside its valid range: arr[arr.Length+1] |
NullReferenceException | Exception | Thrown by the runtime only when a null object is referenced. | object o = null; o.ToString(); |
DivideByZeroException | Exception | Thrown by the runtime only when trying to divide a number by 0 | int a=12/0; |
finally: There is a special block introduced is finally. It is a block that executes compulsorily whether the error is occurring or not. It is executed at last. Generally, finally block is used for cleaning up the resources or closing the database connection, etc.
try
{
// This is a block which may contain an error
}
catch
{
// This block handles the error if the error is thrown by try block
}
finally
{
// This block always executes.
}
Special Notes:
- Exceptions are types that all ultimately derive from
System.Exception
. - Use a
try
block around the statements that might throw exceptions. - Once an exception occurs in the
try
block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, thecatch
keyword is used to define an exception handler. - If no exception handler for a given exception is present, the program stops executing with an error message.
- Do not catch an exception unless you can handle it and leave the application in a known state. If you catch
System.Exception
, rethrow it using thethrow
keyword at the end of thecatch
block. - If a
catch
block defines an exception variable, you can use it to obtain more information about the type of exception that occurred. - Exceptions can be explicitly generated by a program by using the
throw
keyword. - Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.
- Code in a
finally
block is executed even if an exception is thrown. Use afinally
block to release resources, for example to close any streams or files that were opened in thetry
block.
How to use the try/catch block to catch exceptions
Place the sections of code that might throw exceptions in a try
block and place code that handles exceptions in a catch
block. The catch
block is a series of statements beginning with the keyword catch
, followed by an exception type and an action to be taken.
class ExceptionDemo
{
public int divide(int x, int y)
{
int r=x/y;
return r;
}
static void Main()
{
ExceptionDemo ed=new ExceptionDemo();
int result=0;
try
{
result = ed.divide(10, 0);
Console.Write(result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempted divide by zero.");
}
}
}
We can also create Custom Exception class as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace user_defined_exception
{
class Program
{
static void Main(string[] args)
{
int acceptorder;
Console.WriteLine("Welcome to Book Store:\nHow many books you want to buy (Total 10 in Stock):");
acceptorder = Convert.ToInt32(Console.ReadLine());
try
{
if (acceptorder == 10 || acceptorder < 10)
{
Console.WriteLine("Congratulations! You have bought {0} books", acceptorder);
Console.ReadLine();
}
else
{
throw (new OutofStockException("OutofStockException Generated: The number of item you want to buy is out of stock. Please enter total item number within stock"));
}
}
catch (OutofStockException oex)
{
Console.WriteLine(oex.Message.ToString());
Console.ReadLine();
}
}
}
//Creating Custome Exception - OutofStockException
public class OutofStockException : Exception
{
public OutofStockException(string message)
: base(message)
{
}
}
}
Summary:
- So in this article, we learned that what exception, types of exception.
- We also learned that How to use the try/catch block to catch exceptions.
- We have also seen how to create a custom exception class.