Developer

Try… Catch… Win!

As a .NET developer, there are a few "best practices" that you should always consider. And one of the biggest is that every application you write should include error trapping to trap critical and non-critical errors that may occur. And the .NET framework makes it easy to use "Try… Catch" statements to intercept any errors that occur and allow you to handle the exception.

As a .NET developer, there are a few "best practices" that you should always consider. And one of the biggest is that every application you write should include error trapping to trap critical and non-critical errors that may occur. And the .NET framework makes it easy to use "Try… Catch" statements to intercept any errors that occur and allow you to handle the exception.

Another great trick when developing .NET applications for Windows is actually writing out the error messages and any debug statements to an audit log. You can use the code below to take any exception thrown in a Try..Catch statement and write it out to a "Critical Error Log" along with the timestamp of when it occurred.

Dim ErrorOutputFileName

With System.DateTime.Now
ErrorOutputFileName = FolderLocation & "\Critical_Error_Log_" & .Day.ToString & "-" & .Month.ToString & "-" & .Year.ToString & "_" & .Hour.ToString & "-" & .Minute.ToString & ".txt"
End With

Dim sw As New StreamWriter(ErrorOutputFileName, True, System.Text.Encoding.ASCII)
sw.WriteLine(ex.Message)
sw.Close()
Me.Close()

And that is not all… you can use the WriteLine method to write out any other information you will need to troubleshoot, including variable values, system state, etc.

And remember, trapping errors is an easy way to make sure your applications are rock-solid, now and in the future.

Editor's Picks

Free Newsletters, In your Inbox