COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Yoshi
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.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
ISBN Chapter 14 Exception Handling and Event Handling.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11 Exception Handling and Event Handling.
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Java Software Solutions Foundations of Program Design Sixth Edition
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.
Chapter 13, Slide 1 Exception Handling Exception handling is a language feature that allows the programmer to handle runtime "exceptional conditions."
Object Oriented Programming
1 Exceptions (Section 8.5) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael Scott.
ISBN Chapter 14 Exception Handling and Event Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Introduction to Exception Handling and Defensive Programming.
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.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
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.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exceptions in the Java programming language J. W. Rider.
Eighth Lecture Exception Handling in Java
Java Exceptions a quick review….
Exception Handling in C++
Tirgul 13 Exceptions 1.
Java Programming Language
Exception Handling and Reading / Writing Files
Exception Handling.
Exception Handling In Text: Chapter 14.
COP4020 Programming Languages
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exception Handling and Event Handling
Exception Handling.
Presentation transcript:

COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)

COP4020 Fall /1/2015 Overview Defensive programming Ways to catch and handle run-time errors in programming languages that do not support exception handling Exception handling in C++ Exception handling in Java

COP4020 Fall /1/2015 Defensive Programming Defensive programming is a methodology that makes programs more robust to failures  Increases the quality of software Failures may be due to  Erroneous user input (e.g. entering a date in the wrong format)  File format and access problems (e.g. end of file or disk full)  Networks failures  Problems with arithmetic (e.g. overflow)  Hardware and software interrupts (e.g. hitting the break key)

COP4020 Fall /1/2015 Exception Handling Principles The three purposes of an exception handler: 1. Recover from an exception to safely continue execution 2. If full recovery is not possible, display or log error message(s) 3. If the exception cannot be handled locally, clean up local resources and re-raise the exception to propagate it to another handler Exception handling makes defensive programming easier  An exception is an error condition, failure, or other special event  Exceptions are handled by exception handlers to recover from failures  Built-in exceptions are automatically detected by the run-time system and handled by internal handlers or the program aborts  Exceptions can be explicitly raised by the program  Exception handlers can be user-defined routines that are executed when an exception is raised

COP4020 Fall /1/2015 Signal Handlers UNIX signal handlers are a very simple form of exception handlers  The signal () function allows signals to be caught or ignored: signal(SIGINT, SIG_DFL); // default setting signal(SIGINT, SIG_IGN); // ignore signal(SIGINT, handle_quit); // use handler … void handle_quit(int sig) { … } Some useful signals:  SIGINTinterrupt program  SIGFPEfloating point exception  SIGKILLkill program  SIGBUSbus error  SIGSEGVsegmentation violation  SIGPIPEwrite on pipe with no reader  SIGALRMreal-time timer expired

COP4020 Fall /1/2015 Catching Runtime Errors w/o Exception Handlers C, Fortran 77, and Pascal do not support exception handling Other mechanisms to handle errors add "clutter” and obscures the logic of a program Method 1: Functions return special error values  Example in C: int somefun(FILE *fd) {... if (feof(fd)) return -1; // return error code -1 on end of file return value; // return normal (positive) value }  Every function return has to be tested for values indicating an error int val; val = somefun(fd); if (val < 0)...  Forgetting to test can lead to disaster!

COP4020 Fall /1/2015 Catching Runtime Errors w/o Exception Handlers (cont’d) Method 2: Functions and methods set global/object status variable  Global variable holds error status, e.g. in C: int somefun(FILE *fd) { errstat = 0; // reset status variable... if (feof(fd)) errstat = -1; // error detected return value; // return a value anyway }  Another method is to include a status parameter, e.g. in C: int somefun(FILE *fd, int *errstat) { *errstat = 0; // reset status parameter... if (feof(fd)) *errstat = -1; // error detected return value; // return a value anyway }  Must to check status variable after each function call

COP4020 Fall /1/2015 Catching Runtime Errors w/o Exception Handlers (cont’d) Method 3: Pass an error-handling function when invoking a function or method  Example in C: int somefun(FILE *fd, void (*handler)(int)) {... if (feof(fd)) handler(-1); // error detected: invoke handler return value; // return a value }

COP4020 Fall /1/2015 Catching Runtime Errors w/o Exception Handlers (cont’d) Method 4: Use setjmp/longjmp in C to dynamically jump back out through multiple function invocations  Example: #include int main() { jmp_buf jbuf; // jump buffer holds execution context … if (setjmp(jbuf) != 0) // setjmp returns 0 on initialization of context … // handle longjmp’s error here … somefun(); } int somefun() { … if (some_error) longjmp(jbuf, 10); // jump to the setjmp(), which returns 10 … }  Warning: use longjmp in C only, because destructors of local objects won’t be invoked

COP4020 Fall /1/2015 Exception Handling Implementation In most programming languages, exception handlers are attached to a specific collection of program statements that can raise exception(s) When an exception occurs in this collection of statements, a handler is selected and invoked that matches the exception If no handler can be found, the exception is propagated to exception handlers of the outer scope of the statements, or if no handler exists in the outer scope, to the caller of the subroutine/method When propagating the unhandled exception to the caller, the current subroutine/method is cleaned up:  Subroutine frames are removed and destructor functions are called to deallocate objects

COP4020 Fall /1/2015 Exception Handling in C++ C++ has no built-in exceptions:  Exceptions are user-defined  STL defines a few useful exceptions  Exceptions have to be explicitly raised with throw An exception in C++ is a type (typically a class):  class empty_queue { public empty_queue(queue q) {... };... // constructor that takes a queue object for diagnostics }; declares an “empty queue” exception  short int eof_condition; declares a variable used to raise a "short int" exception

COP4020 Fall /1/2015 Exception Handling in C++ (cont’d) C++ exception handlers are attached to a block of statements with the try -block and a set of catch -clauses (or catch -blocks): try { … … throw eof_condition; // matches short int exception … throw empty_queue(myq); // matches the empty_queue exception and // passes the myq object to handler … throw 6; // matches int exception and sets n=6 … } catch (short int) { … // handle end of file (no exception parameter) } catch (empty_queue e) { … // handle empty queue, where parameter e is the myq empty_queue object } catch (int n) { … // handle exception of type int, where parameter n is set by the throw } catch (...) { … // catch-all handler (ellipsis) }

COP4020 Fall /1/2015 Exception Handling in C++ (cont’d) A catch -block is executed that matches the type/class of throw  A catch specifies a type/class and an optional parameter  Can pass the exception object by value or by reference  The parameter has a local scope in the catch -block The catch (...) with ellipsis catches all remaining exceptions After an exception is handled:  Execution continues with statements after the try-catch and all local variables allocated in the try-block are deallocated  If no handler matches an exception (and there is no catch with ellipsis), the current function is terminated and the exception is propagated to the caller of the function: try { afun(); // may throw empty queue exception that it doesn’t catch } catch (empty_queue) {... // handle empty queue exception here }

COP4020 Fall /1/2015 Exception Handling in C++ (cont’d) C++ supports exception hierarchies:  An exception handler for exception class X also catches derived exceptions Y of base class X: class X {…}; class Y: public X {…}; … try { … } catch (X& e) { … // handle exceptions X and Y } In C++, functions and methods may list the types of exceptions they may raise: int afun() throw (int, empty_queue) {... } where afun can raise int and empty_queue exceptions, as well as derived exception classes of empty_queue

COP4020 Fall /1/2015 Exception Handling in Java All Java exceptions are objects of classes that are descendants of class Throwable Classes Error and Exception are descendants of Throwable  Error : built-in exceptions such as "out of memory"  Exception : all user-defined exceptions are derived from Exception  RuntimeException : base class for built-in dynamic semantic errors, such as IOException for I/O exceptions Example user-defined exception: class MyException extends Exception { public MyException() {}; public MyException(String msg) { super(msg); // class Exception handles the message } }

COP4020 Fall /1/2015 Exception Handling in Java (cont’d) An exception is explicitly raised with throw : Examples: throw new MyException(); throw new MyException("some error message"); The syntax of the catch -handlers in Java is the same as C++, but Java also has an optional finally block: try {... } catch (MyException e) {... // catch exceptions that are (descendants of) MyException } catch (Exception e) {... // a catch-all handler: all exceptions are descendants of Exception } finally {... // always executed for clean-up operations }

COP4020 Fall /1/2015 Exception Handling in Java (cont’d) The finally block is always executed, even when a break or return statement is executed in the try-block A catch -handler for an exception also handles exceptions that are descendents of that exception class After an exception is handled in a catch -block:  Execution continues with the statements in the finally block (if any)  And then the statements that follow the try-catch blocks If no handler matches the raised exception:  The current method is terminated  The finally block executed (if any)  Exception is propagated to the caller

COP4020 Fall /1/2015 Exception Handling in Java (cont’d) Java class methods must list the exceptions that they may raise:  Those that can be raised by the system and are not locally caught  Those that explicitly raised by throw and are not locally caught  For example: class GradeList {... void BuildDist() throws IOException {... // I/O operations here may raise IOException }... } The Java compiler will verify the list of exceptions for completeness The exception classes Error and RuntimeException and their descendants are unchecked exceptions and are not verified by the compiler and do not need to be listed There are no default exception handlers or catch-all handlers  For a catch-all: Exception catches any exception