A program can use try-catch-finally
blocks to protect itself from exceptions. The syntax is as follows.
try
{
tryStatements...
}
catch (exceptionType1 variable1)
{
exceptionStatements1...
}
catch (exceptionType2 variable2)
{
exceptionStatements2...
}
...
catch
{
finalExceptionStatements...
}
finally
{
finallyStatements...
}
When an error occurs, the program examines the catch
statements in order until it finds one that matches the current exception and executes the corresponding code. If the exception doesn’t match any of the catch
statements, the program executes the code in the final catch
statement, which doesn’t specify an exception type.
After executing the code in the try
section and possibly a catch
section, the program executes the code in the finally
section.
The catch
and finally
sections are optional; although, the try-catch-finally
block must include at least one catch
section or the finally
section.
Use the throw
statement to throw an exception, as in the following code.
throw new ArgumentException("Width must be greater than zero");
Exception classes provide several overloaded constructors, so you can indicate such things as the basic error message, the name of the variable that caused the exception, and an inner exception.
For information on useful exception classes and custom exception classes, see Appendix O, “Useful Exception Classes.”