C# Exception Handling
An exception is a problem that occurs during program execution. An exception in C# is a response to an exceptional situation that occurs while the program is running, 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 on four keywords:try、catch、finally and throw。
- try: a try block identifies a specific block of code for which a particular exception will be activated. It is followed by one or more catch blocks.
- catch: the program catches the exception through an exception handler. The catch keyword indicates the catching of an exception.
- finally: the finally block is used to execute a given set of statements, whether or not an exception is thrown. For example, if you open a file, the file must be closed regardless of whether an exception occurs.
- throw: when a problem occurs, the program throws an exception. This is done using the throw keyword.
Syntax
Assume that an exception will occur in a block; a method uses the try and catch keywords to catch the exception. The code inside the try/catch block is protected code. The try/catch syntax is as follows:
try
{
// Statements that cause the exception
}
catch
(
ExceptionName e1
)
{
// Error handling code
}
catch
(
ExceptionName e2
)
{
// Error handling code
}
catch
(
ExceptionName eN
)
{
// Error handling code
}
finally
{
// Statements to execute
}
You can list multiple catch statements to catch different types of exceptions, in case the try block generates multiple exceptions under different circumstances.
Exception Classes in C#
Exceptions in C# are represented using classes. The exception classes in C# mainly derive directly or indirectly from System.Exception class.System.ApplicationException and System.SystemException class is an exception class derived from the System.Exception class.
System.ApplicationException class supports exceptions generated by an application. Therefore, programmer-defined exceptions should all derive from this class.
System.SystemException class is the base class of all predefined system exceptions.
The following table lists some predefined exception classes derived from the System.SystemException class:
| Exception classes | Description |
|---|---|
| System.IO.IOException | Handles I/O errors. |
| System.IndexOutOfRangeException | Handles errors generated when a method points to an array index out of range. |
| System.ArrayTypeMismatchException | Handles errors generated when array types do not match. |
| System.NullReferenceException | Handles errors generated when dereferencing a null object. |
| System.DivideByZeroException | Handles errors generated when dividing by zero. |
| System.InvalidCastException | Handles errors generated during type conversion. |
| System.OutOfMemoryException | Handles errors generated when free memory is insufficient. |
| System.StackOverflowException | Handles errors generated when the stack overflows. |
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 using the try、catch and finally keyword. The following is an example of throwing an exception when dividing by zero:
Example
using
System
;
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 code above 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. A user-defined exception class derives from the ApplicationException class. The following example illustrates this:
Example
using
System
;
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 code above is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found
Throwing Objects
If an exception derives directly or indirectly from the System.Exception class, you can throw an object. You can use a throw statement in a catch block to throw the current object, as shown below:
Catch(Exception e)
{
...
Throw e
}