1 Exceptions (Section 8.5) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael Scott.

Slides:



Advertisements
Similar presentations
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Advertisements

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
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 13 In a language without exception handling: When an exception occurs, control goes to the operating.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Run time vs. Compile time
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
PZ11A Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ11A - Exception handling Programming Language Design.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Object Oriented Programming
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Slides Credit Umair Javed LUMS Web Application Development.
1 Subroutines and Control Abstraction Aaron Bloomfield CS 415 Fall 2005.
Copyright © 2005 Elsevier Chapter 8 :: Subroutines and Control Abstraction Programming Language Pragmatics Michael L. Scott.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Lecture 19: Control Abstraction (Section )
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.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
1 Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Eighth Lecture Exception Handling in Java
Part IX Fundamentals of C and C++ Programming Exception Handling
Chapter 9 :: Subroutines and Control Abstraction
CS 3304 Comparative Languages
Chap. 8 :: Subroutines and Control Abstraction
Chap. 8 :: Subroutines and Control Abstraction
Exception Handling Chapter 9 Edited by JJ.
Exception Handling In Text: Chapter 14.
COP4020 Programming Languages
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Lecture 11 Objectives Learn what an exception is.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Presentation transcript:

1 Exceptions (Section 8.5) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael Scott

2 Exception Handling ExceptionException –unusual condition detected at run time –may require to "back-out" from several levels of subroutine calls Examples:Examples: "Traditional" ways to handle such situations:"Traditional" ways to handle such situations: –arithmetic overflow –end-of-file on input –wrong type for input data –user-defined conditions (not necessarily errors), raised explicitly –return some default value when the real one cannot be obtained –return (or have an extra parameter) an explicit "status" value, to be inspected after each call –pass a closure for error handling, to be called in case of trouble

3 Exception Handling Example (C++):Example (C++): void f () {...try{ g(); g();} catch (exc) { // handle exception of type exc // handle exception of type exc}...} void g () {...h();...} void h() {... if (...) throw exc; throw exc;...}

4 Exception Handling Exception handlerException handler –code executed when exception occurs –different handler for each type of exception Introduced by PL/I:Introduced by PL/I: ON condition statement –the statement is "remembered" for later use, if the condition (e.g. OVERFLOW) arises –if the condition arises: »execute statement »for "fatal" errors - terminate program »for "recoverable" errors – jump back to where exception occurred and continue execution

5 Exception Handling C++, Ada, Java, ML – more structured approach:C++, Ada, Java, ML – more structured approach: –handlers (catch in C++) are lexically bound to blocks of protected code (the code inside a try block in C++) Exception propagation:Exception propagation: –if an exception is raised (throw in C++): »if the exception is not handled in the current subroutine, return abruptly from subroutine »return abruptly from each subroutine in the dynamic chain of calls, until a handler is found »if found, execute the handler, then continue with code after handler »if no handler is found until outermost level (main program), terminate program

6 Exception Handling Usage for exception handling mechanisms:Usage for exception handling mechanisms: –perform operations to recover, and then continue execution »allocate more memory »recover from errors in a compiler –handle errors exactly where we want, without checking for them explicitly everywhere they might occur –subroutine documentation – specify what exceptions might be raised by a subroutine → subroutine user may want to catch them –cannot recover locally, but: »may want a local handler just to clean up some local resources »then re-raise the exception to be handled by a "higher authority" –terminate, but first print a helpful error message Advantages:Advantages: –uniform manner of handling errors

7 Hierarchy of Exceptions In PL/1, exception do not have a typeIn PL/1, exception do not have a type In Ada, all exceptions are of type exceptionIn Ada, all exceptions are of type exception –Exception handler can handle one specific exception or all of them Since exceptions are classes in Java, exception handlers can capture an entire class of exceptions (parent classes and all its derived classes)Since exceptions are classes in Java, exception handlers can capture an entire class of exceptions (parent classes and all its derived classes) –Hierarchy of exceptions

8 Definition of Exceptions Exception types:Exception types: –Predefined – dynamic semantic errors: »arithmetic overflow »division by zero »end-of-file on input »subscript and subrange out of bounds »null pointer dereference –User-defined: declare empty_queue : exception;-- Ada class empty_queue { };// C ++

9 Definition of Exceptions Parameterized exceptions – the code which raises the exception can pass additional information with itParameterized exceptions – the code which raises the exception can pass additional information with it –C++: class duplicate_in_set { item dup;// element that was inserted twice }... throw duplicate_in_set (d); –ML: exception duplicate_in_set of item;... raise duplicate_in_set (d); –Ada, Common Lisp: »exceptions are just tags – no other information than the exception name

10 Definition of Exceptions Documenting exceptions:Documenting exceptions: –Modula-3 – mandatory to declare (in the subroutine header) all exceptions that may propagate out of the subroutine »if another exception propagates (not caught internally) → run-time error –C++ – optional list of exceptions »if the list is specified → same behavior as in Modula-3 »if the list is omitted → any exception can propagate –Java »“checked” exceptions – must be declared in subroutine headers »“unchecked” exceptions – may be omitted (e.g. fatal errors – array subscript out of bounds)

11 Exception Propagation Exception handler – attached to a block of code (protected code)Exception handler – attached to a block of code (protected code) –Ada: with text_io;-- import I/O routines (and exceptions) procedure read_record (...) is begin...begin protected code - potentially complex sequence of operations -- involving many calls to text_io.get...exception when end_error => handler to catch any attempt to read past end_of_file -- in any of the I/O calls end;... end read_record;

12 Exception Propagation –C++ (predefined exceptions): try {... // protected block of code...} catch (end_of_file) {...} catch (io_error e) {// any io_error other than end_of_file...} catch (...) {// all other exceptions;... is part of syntax...} »handler matches exception if it names a class from which exception is derived »can declare an exception object (e) – access additional information passed with the exception

13 Exception Handlers Java Java uses lexically scoped exception handlersJava uses lexically scoped exception handlers try { int a[] = new int[2]; int a[] = new int[2]; a[4]; a[4]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("exception: " + e.getMessage()); System.out.println("exception: " + e.getMessage()); e.printStackTrace(); e.printStackTrace();} The dynamic chain is available using printStackTrace()The dynamic chain is available using printStackTrace() – ang/Throwable.html ang/Throwable.htmlhttp://java.sun.com/products/jdk/1.2/docs/api/java/l ang/Throwable.html

14 Implementation Linked-list of dynamically-bound handlers maintained at run-timeLinked-list of dynamically-bound handlers maintained at run-time –Each subroutine has a default handler that takes care of the epilogue before propagating an exception –This is slow, since the list must be updated for each block of code Compile-time table of blocks and handlersCompile-time table of blocks and handlers –Two fields: starting address of the block and address of the corresponding handler –Exception handling using a binary search indexed by the program counter –Logarithmic cost on the number of handlers

15 Java Each subroutine has a separate exception handling tableEach subroutine has a separate exception handling table –Thanks to independent compilation of code fragments Each stack frame contains a pointer to the appropriate tableEach stack frame contains a pointer to the appropriate table

16 C Exception can be simulatedException can be simulated setjmp() can store a representation of the current program state in a buffersetjmp() can store a representation of the current program state in a buffer –Returns 0 if normal return, 1 if return from long jump longjmp() can restore this statelongjmp() can restore this state Example:Example: if (!setjmp(buffer)) { /* protected code */ } else { /* handler */ } For more information: LongjmpFor more information: LongjmpLongjmp

17 C The state is usually the set of registersThe state is usually the set of registers longjmp() restores this set of registerslongjmp() restores this set of registers – 0.02/library_20.html /library_20.htmlhttp:// 0.02/library_20.html Is this good enough?Is this good enough? Changes to variables before the long jump are committed, but changes to registers are ignoredChanges to variables before the long jump are committed, but changes to registers are ignored If the handler needs to see changes to a variable that may be modified in the protected code, the programmer must include the volatile keyword in the variable’s declarationIf the handler needs to see changes to a variable that may be modified in the protected code, the programmer must include the volatile keyword in the variable’s declaration