Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 3260 Dennis A. Fairclough Version 1.0

Similar presentations

Presentation on theme: "CS 3260 Dennis A. Fairclough Version 1.0"— Presentation transcript:

1 CS 3260 Dennis A. Fairclough Version 1.0
Exception Handling CS 3260 Dennis A. Fairclough Version 1.0

2 Overview Exception Handling in C# try-catch-finally clauses throw

3 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

4 C# .NET Software Development Version 1.0
C# Exceptions & Errors C# .NET Software Development Version 1.0

5 Common Exception Classes
System.ArithmeticException A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException. System.ArrayTypeMismatchException Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array. System.DivideByZeroException Thrown when an attempt to divide an integral value by zero occurs. System.IndexOutOfRangeException Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array. System.InvalidCastException Thrown when an explicit conversion from a base type or interface to a derived type fails at run time. System.NullReferenceException Thrown when a null reference is used in a way that causes the referenced object to be required. System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails. System.OverflowException Thrown when an arithmetic operation in a checked context overflows. System.StackOverflowException Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion. System.TypeInitializationException Thrown when a static constructor throws an exception, and no catch clauses exists to catch it.

6 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

7 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{ }

8 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

9 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 +y –y +0 –0 +∞ –∞ NaN +x +z –z –x

10 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

11 throw The throw statement throws an exception.
throw-statement: throw expressionopt ; 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

12 Re-throw catch(Exception exp) { throw; or throw new XException(); }

13 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

14 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

15 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

16 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

17 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. InnerException is 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

18 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

19 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

20 Order is Important Wrong (why?) Right void function1() {
try { // code } catch(Exception ex) catch(Exception1 ex) { } void function1() { try { // code } catch(Exception1 ex) catch(Exception ex) { } // if no rethrow occurs // execution resumes here

21 Exception Flow Control
The exception is passed up the call-stack until a suitable exception handler is found catch(XException xexp) { MessageBox.Show(xexp.message,xexp.StackTrace); } If no suitable handler (catch clause) is found, the exception is passed to the calling method.

22 Unhandled Exceptions If no error handler is found the application terminates Control is passed back to Windows Exception Handler!

23 finally clause Must be associated with a try block
a try block may have one finally block finally block always gets executed, regardless! If required, the appropriate catch clause is executed first

24 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! catch with no parameters is intended for none C# exceptions Hardware Exceptions Other Language Exceptions

25 Built-In Exceptions ArithmeticException ArrayTypeMismatchException
DivideByZeroException IndexOutOfRangeException InvalidCastException NullReferenceException OutOfMemoryException OverflowException StackOverflowException TypeInitializationException Many more….

26 System.Exception class
Properties                                                   Name Description Data Gets a collection of key/value pairs that provide additional user-defined information about the exception. HelpLink Gets or sets a link to the help file associated with this exception. HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. InnerException Gets the Exception instance that caused the current exception. Message Gets a message that describes the current exception. Source Gets or sets the name of the application or the object that causes the error. StackTrace Gets a string representation of the frames on the call stack at the time the current exception was thrown. TargetSite Gets the method that throws the current exception.

27 IDE Exception Processing
Ctrl + Alt + E Ctrl + Alt + E

28 Design Considerations
Use exceptions in place of method return codes Exceptions are only costly if used (thrown), then very costly! Centralizes error handling

Download ppt "CS 3260 Dennis A. Fairclough Version 1.0"

Similar presentations

Ads by Google