CS 3260 Dennis A. Fairclough Version 1.0

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
CSE 1302 Lecture 21 Exception Handling and Parallel Programming Richard Gesick.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Try…Catch…Finally Blocks ( continued ) Generic catch clause –Omit argument list with the catch –Any exception thrown is handled by executing code within.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Chapter 11 Debugging and Handling Exceptions
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Introduction to Programming Lesson 1. Objectives Skills/ConceptsMTA Exam Objectives Understanding Computer Programming Understand computer storage and.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
1 More on Threads b b A section of code executed independently of other threads written within a single program. b b Java threads can access global data;
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Dr. Abraham. Exception Any problem that VB or OS could not handle Robust program A program that performs well not only under ordinary conditions but also.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Object Oriented Programming
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Debugging and Handling Exceptions
Why exception handling in C++?
CNS 3260 C# .NET Software Development
Programming in C# CHAPTER - 7
Presentation transcript:

CS 3260 Dennis A. Fairclough Version 1.0 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# .NET Software Development Version 1.0 C# Exceptions & Errors C# .NET Software Development Version 1.0

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.

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

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: 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

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. 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

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

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.

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 finally block 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! catch with 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                                                   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.

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