Error handling covers those cases where something unintended happens, such as
the user runing out of disk space, or the database server being unavailable.
The try/catch error handling mechanism provides a way for you to "try" and
execute some code, and "catch" any problems that occur and handle them
programmatically.
If you are looking to handle errors in the validity of data in a data entry
form, see the section on Validation.
Try/Catch
Exceptions are handled by what is known as a try/catch block. You bracket the
code that can possibly throw an exception in a try { ... } block. Next, you
follow this with one or more catch { ... } blocks where you put code that
should execute when a specific or general type of exception is thrown. The
following code snippet shows the framework for handling data exceptions:
try { //Do some work...
} catch(SqlException
ex) { //Catch specific SqlExceptions
} catch(Exception
ex) { //Catch general Exceptions
}
If you want to pass the exception to the caller, you can re-throw the exception. The following catch block throws SqlExceptions to the caller for handling:
catch(SqlException
ex) { //Catch and Re-Throw SqlExceptions
throw ex; }
Writing to the Event Log
Often when an error occurs, applications will write an event to the Windows Event Log. This is particularly prevalent in services, where a user may not be present to view details about an error when it happens.
The EventLog class in the System.Diagnostics namespace provides a simple mechanism for writing to the Event Log. This class has a WriteEntry method that writes an event to the log.
Here is an example:
// Writing to the Event Log via Static Method
EventLog.WriteEntry("WinApp316","The windows application, WinApp316, has been started.", EventLogEntryType.Information);
// Writing to the Event Log via Instance Method
EventLog objLog=new EventLog(); objLog.Source ="WinApp316"; objLog.Log ="Application"; objLog.WriteEntry("The windows application, WinApp316, has been started.", EventLogEntryType.Information);