140 likes | 376 Views
Exception Handling. By Sam Nasr, MCP May 22, 2007. www.ClevelandDotNet.info. Agenda. Introduction Exception Handling Break Open Forum Q&A Survey. Exception Handling. Used to handle errors Uses Try/Catch/Finally blocks Throw errors Other classes derive from Exception{} base class.
E N D
Exception Handling By Sam Nasr, MCP May 22, 2007 www.ClevelandDotNet.info
Agenda • Introduction • Exception Handling • Break • Open Forum • Q&A • Survey
Exception Handling • Used to handle errors • Uses Try/Catch/Finally blocks • Throw errors • Other classes derive from Exception{} base class
Exception Classes • SQLException • SQLTypeException • DataException • SOAPException
SOAPException Class • Code: returns the SOAP fault code • Actor: identifies the code that causes the exception • Source: returns the name of the assembly where the application occurs • Detail: returns an XMLNode object that describes the exception.
User Defined Exception Classes • Public Class EmployeeListNotFoundException • Inherits Exception • OR • public class MyFileNotFoundException :Exception • { • }
Best Practices • Programmatically check for a condition that is likely to occur without using exception handling. If conn.State <> ConnectionState.Closed Then conn.Close() End If As opposed to: Try conn.Close() Catch ex As InvalidOperationException 'Do something with the error or ignore it. End Try
Best Practices • Design classes so that an exception is never thrown in normal use. • Class FileRead • Sub Open() • Dim stream As FileStream = _ File.Open("myfile.txt", FileMode.Open) • Dim b As Byte • Dim result As Integer ' ReadByte returns -1 at EOF. • Do result = stream.ReadByte() • If result = -1 Then Exit Do • b = CByte(result) • ' Do something. • Loop • ' Call stream.Close() here or in another method. • End Sub 'Open • End Class 'FileRead
Best Practices • Throw exceptions instead of returning an error code or HRESULT. • Clean up intermediate results when throwing an exception. • Use grammatically correct error messages. • Provide Exception properties for programmatic access. Include extra information in an exception (in addition to the description string) only when there is a programmatic scenario where the additional information is useful. • Return null for extremely common error cases.
Best Practices • Use try/finally blocks around code that can potentially generate an exception and centralize your catch statements in one location. • Always order exceptions in catch blocks from the most specific to the least specific. • In most cases, use the predefined exceptions types.
Resources MSDN Patterns & Practices http://msdn2.microsoft.com/en-us/library/seyhszts.aspx MSDN Exception Handling Application Block http://msdn2.microsoft.com/en-us/library/aa480461.aspx Exception Handling Best Practices in .NET http://www.codeproject.com/dotnet/exceptionbestpractices.asp Try...Catch...Finally Statements http://msdn2.microsoft.com/en-us/library/fk6t46tz(VS.71).aspx