C# Exception Handling
An exception is a problem that arises during the execution of a program. Exceptions in C# are a response to exceptional situations that occur at runtime, such as attempting to divide by zero.
Exceptions provide a way to transfer program control from one part to another. C# exception handling is built upon four keywords:try、catch、finallyandthrow。
- try: A try block identifies a block of code for which a particular exception will be activated. It is followed by one or more catch blocks.
- catch: The program catches an exception through an exception handler. The catch keyword indicates the catching of an exception.
- finally: The finally block is used to execute the given statements, regardless of whether an exception is thrown. For example, if you open a file, the file will be closed whether or not an exception occurs.
- throw: When a problem occurs, the program throws an exception. This is done using the throw keyword.
Syntax
Assuming a block will raise an exception, a method uses the try and catch keywords to catch the exception. The code within a try/catch block is protected code, and the try/catch syntax is shown below:
{
// Statement that caused the exception
}
catch( ExceptionName e1 )
{
// Error handling code
}
catch( ExceptionName e2 )
{
// Error handling code
}
catch( ExceptionName eN )
{
// Error handling code
}
finally
{
// Statement to execute
}
You can list multiple catch statements to catch different types of exceptions, in case the try block generates multiple exceptions in different situations.
Exception classes in C#
C# exceptions are represented using classes. The exception classes in C# are mainly directly or indirectly derived fromSystem.Exceptionclass.System.ApplicationExceptionandSystem.SystemExceptionThe class is an exception class derived from the System.Exception class.
System.ApplicationExceptionthe class supports exceptions generated by applications. Therefore programmer-defined exceptions should all derive from this class.
System.SystemExceptionThe class is the base class for all predefined system exceptions.
The following table lists some predefined exception classes derived from the System.SystemException class:
| Exception class | Description |
|---|---|
| System.IO.IOException | Handling I/O errors. |
| System.IndexOutOfRangeException | Handles errors generated when a method accesses an array index that is out of range. |
| System.ArrayTypeMismatchException | Handles errors generated when array types do not match. |
| System.NullReferenceException | Handles errors generated when referencing a null object. |
| System.DivideByZeroException | Handling errors generated when dividing by zero. |
| System.InvalidCastException | Handles errors generated during type conversion. |
| System.OutOfMemoryException | Handling errors generated by insufficient free memory. |
| System.StackOverflowException | Handling errors generated by stack overflow. |
Exception Handling
C# provides a structured exception handling scheme in the form of try and catch blocks. Using these blocks, core program statements are separated from error handling statements.
These error handling blocks are implemented usingtry、catchandfinallykeywords. The following is an example of throwing an exception when dividing by zero:
Example
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
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)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ... Result: 0
Creating user-defined exceptions
You can also define your own exceptions. User-defined exception classes are derived fromApplicationExceptionClass. The following example demonstrates this:
Example
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found
Thrown Object
If the exception is directly or indirectly derived fromSystem.Exceptionthe class, and you can throw an object. You can use the throw statement in a catch block to throw the current object, as shown below:
Catch(Exception e)
{
...
Throw e
}
other extensions