970 likes | 2.23k Views
Exception Handling. CS 3260 Dennis A. Fairclough Version 1.0. Overview. Exception Handling in C# try-catch-finally clauses throw Re-throw. Error Detection.
E N D
Exception Handling CS 3260 Dennis A. Fairclough Version 1.0
Overview • Exception Handling in C# • try-catch-finally clauses • throw • Re-throw
Error Detection • Exception handling provides a structured and extensible approach to error detection and recovery; and the type-safe design of the language. C# Language Specification V1.2
C# Exceptions & Errors C# .NET Software Development Version 1.0
Purpose … exception handling provides a structured and extensible approach to error detection and recovery; and the type-safe design of the language makes it impossible to read from uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts. C# 3.0 Specification
Exception Structure • try{ } clause • catch(…){ } clause • finally{ } clause • throw <exception object> • throw – re-throw • All versions • try{ }catch(…){ } • try{ }finally{ } • try{ }catch(…){ }finally{ } • try{ }catch(…){ }catch(…){ }catch{ }finally{ }
Floating Point Exceptions The floating-point operators, including the assignment operators, never produce exceptions. Instead, in exceptional situations, floating-point operations produce zero, infinity, or NaN, as described below: • If the result of a floating-point operation is too small for the destination format, the result of the operation becomes positive zero or negative zero. • If the result of a floating-point operation is too large for the destination format, the result of the operation becomes positive infinity or negative infinity. • If a floating-point operation is invalid, the result of the operation becomes NaN. • If one or both operands of a floating-point operation is NaN, the result of the operation becomes NaN. • C# 3.0 Specification
Floating Point Exceptions • The product is computed according to the rules of IEEE 754 arithmetic. The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s. In the table, x and y are positive finite values. z is the result of x*y. If the result is too large for the destination type, z is infinity. If the result is too small for the destination type, z is zero. C# 3.0 Specification
goto’s In addition to the reachability provided by normal flow of control, a labeled statement is reachable if the label is referenced by a reachable goto statement. (Exception: If a goto statement is inside a try that includes a finally block, and the labeled statement is outside the try, and the end point of the finally block is unreachable, then the labeled statement is not reachable from that goto statement.) C# 3.0 Specification
throw The throw statement throws an exception. throw-statement:throwexpressionopt; A throw statement with an expression throws the value produced by evaluating the expression. The expression must denote a value of the class type System.Exception, of a class type that derives from System.Exception or of a type parameter type that has System.Exception (or a subclass thereof) as its effective base class. If evaluation of the expression produces null, a System.NullReferenceException is thrown instead. A throw statement with no expression can be used only in a catch block, in which case that statement re-throws the exception that is currently being handled by that catch block. Because a throw statement unconditionally transfers control elsewhere, the end point of a throw statement is never reachable. • When an exception is thrown, control is transferred to the first catch clause in an enclosing try statement that can handle the exception. The process that takes place from the point of the exception being thrown to the point of transferring control to a suitable exception handler is known as exception propagation. Propagation of an exception consists of repeatedly evaluating the following steps until a catch clause that matches the exception is found. In this description, the throw point is initially the location at which the exception is thrown. C# 3.0 Specification
Re-throw catch(Exception exp) { throw; or throw new XException(); }
General catch clause Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code. A general catch clause may be used to catch such exceptions. Thus, a general catch clause is semantically different from one that specifies the type System.Exception, in that the former may also catch exceptions from other languages. C# 3.0 Specification
finally clause The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement. C# 3.0 Specification
Exception Class(es) Exceptions in C# provide a structured, uniform, and type-safe way of handling both system level and application level error conditions. The exception mechanism in C# is quite similar to that of C++, with a few important differences: • In C#, all exceptions must be represented by an instance of a class type derived from System.Exception. In C++, any value of any type can be used to represent an exception. • In C#, a finally block (§8.10) can be used to write termination code that executes in both normal execution and exceptional conditions. Such code is difficult to write in C++ without duplicating code. • In C#, system-level exceptions such as overflow, divide-by-zero, and null dereferences have well defined exception classes and are on a par with application-level error conditions. C# 3.0 Specification
Causes of Exceptions Exception can be thrown in two different ways. • A throw statement (§8.9.5) throws an exception immediately and unconditionally. Control never reaches the statement immediately following the throw. • Certain exceptional conditions that arise during the processing of C# statements and expression cause an exception in certain circumstances when the operation cannot be completed normally. • For example, an integer division operation (§7.7.2) throws a System.DivideByZeroException if the denominator is zero. See §16.4 for a list of the various exceptions that can occur in this way. • C# 3.0 Specification
System.Exception • The System.Exception class is the base type of all exceptions. This class has a few notable properties that all exceptions share: • Message is a read-only property of type string that contains a human-readable description of the reason for the exception. • InnerExceptionis a read-only property of type Exception. If its value is non-null, it refers to the exception that caused the current exception—that is, the current exception was raised in a catch block handling the InnerException. Otherwise, its value is null, indicating that this exception was not caused by another exception. The number of exception objects chained together in this manner can be arbitrary. • The value of these properties can be specified in calls to the instance constructor for System.Exception. • C# 3.0 Specification
Exceptions in C# • Must inherit from System.Exception • Standard error handling in C# • Are thrown when: • the code reaches a throw statement • Thrown as system exceptions (i.e. divide by zero) • Hardware or other software (C++) exceptions
Rules • A try block must have one or more associated catch blocks or a finally block • A catch block must be associated with a try block • A try block may have zero or more catch blocks • catch blocks catch the exception type or any derived exception types passing through • catch blocks are searched in the order they appear in the code • catch blocks for specific types must come before the more general types • An Empty catch clause will catch any exception type (useful for bad errors!) • catch clauses don’t need, but should have, a variable name • catch(Exception) or catch works, but deprecated don’t use
Order is Important Right Wrong (why?) void function1(){ try { // code } catch(Exception1 ex) { } catch(Exception ex) { } // if no rethrow occurs // execution resumes here } void function1(){ try { // code } catch(Exception ex) { } catch(Exception1 ex) { } }
Exception Flow Control • The exception is passed up the call-stack until a suitable exception handler is found catch(XExceptionxexp) { MessageBox.Show(xexp.message,xexp.StackTrace); } • If no suitable handler (catch clause) is found, the exception is passed to the calling method.
Unhandled Exceptions • If no error handler is found the application terminates • Control is passed back to Windows Exception Handler!
finally clause • Must be associated with a try block • a try block may have one finallyblock • finally block always gets executed, regardless! • If required, the appropriate catch clause is executed first
Unhandled Exceptions • Unhandled Exception in a destructor • destructor stops executing, exception is discarded, base destructor is called • catch (with no parameter) will catch all exceptions, including unmanaged exceptions. Really catch(Exception) use this version! • catchwith no parameters is intended for none C# exceptions • Hardware Exceptions • Other Language Exceptions
Built-In Exceptions • ArithmeticException • ArrayTypeMismatchException • DivideByZeroException • IndexOutOfRangeException • InvalidCastException • NullReferenceException • OutOfMemoryException • OverflowException • StackOverflowException • TypeInitializationException • Many more….
System.Exception class Properties
IDE Exception Processing Ctrl + Alt + E Ctrl + Alt + E
Design Considerations • Use exceptions in place of method return codes • Exceptions are only costly if used (thrown), then very costly! • Centralizes error handling