CS 112D Lecture Notes - Exception Handling
Exception Handling
- To catch (handle) an exception, use a try block together with a catch block.
- Try is a keyword that begins a block of code in which any exceptions that occur will be
handled. If an exception occurs in a try block, the code jumps out of that try block to the appropriate
catch block.
- Catch is a keyword that begins a block of code in which a class of exception is handled. The
code in a catch block is executed only if an exception is thrown from within the immediately preceding
try block. Each catch block specifies a specific exception class. That catch block is only executed if
an Exception of that class (or a subclass of it) is thrown.
- A catch block is much like a function, with a single parameter of the exception object. This
"function" is called automatically when a matching exception is thrown from the try block immediately
preceding it.
- Finally is a keyword that begins a block of code after a set of catch blocks, containing code
that is always executed whether or not an exception occurred. The "finally" block is optional when
handling exceptions.
- If an exception is not caught by the function in which it is thrown, then the exception propagates
to the calling function. In other words, exceptions travel down the call stack until they are caught.
If no function catches the exception, the program terminates and displays an error message (a run-time
error).
- Here are some common Exception classes you might want to handle:
- InvalidCastException - occurs when an error occurs trying to convert data types, such as
using CInt with a non-numeric string argument.
- NullReferenceException - occurs when a reference variable storing the value Nothing has one
of its members accessed, such as a method being called on it.
- Data.ConstraintException - occurs when a UniqueConstraint is violated in a DataSet or a
DataTable.
- Data.InvalidConstraintException - occurs when a ForeignKeyConstraint is violated in a
DataSet or DataTable.
- DBConcurrencyException - occurs when a DataAdapter finds no match for the "where" clause in
an update command it executed. Generally, this is because of a concurrency violation: someone else
modified the data you were modifying, and their change was saved in the database before yours was.
- System.Data.SqlClient.SqlException - occurs when a database error occurs while executing a
SqlCommand object. (Such as foreign key violation in the database, not caught by DataSet)
- System.IO.FileNotFoundException - occurs when a file cannot be opened (e.g. a text file)
Return to the main CS 112D page