COP4020 Programming Languages. Exception Handling Prof. Robert van Engelen

Similar documents
Defensive Programming

14. Exception Handling

CS213. Exceptional Control Flow Part II. Topics Process Hierarchy Signals

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal.

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

G Programming Languages - Fall 2012

Sri Vidya College of Engineering & Technology Question Bank

ECE 650 Systems Programming & Engineering. Spring 2018

Signals, Synchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Signals. Joseph Cordina

ECE 122. Engineering Problem Solving with Java

Computer Science & Engineering Department I. I. T. Kharagpur. Operating System: CS rd Year CSE: 5th Semester (Autumn ) Lecture VII

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Chapter 14. Exception Handling and Event Handling

Signals are a kernel-supported mechanism for reporting events to user code and forcing a response to them. There are actually two sorts of such

Operating Systems 2010/2011

Chapter 14. Exception Handling and Event Handling ISBN

Java Loose Ends. 11 December 2017 OSU CSE 1

Assertions and Exceptions Lecture 11 Fall 2005

KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 6

National University. Faculty of Computer Since and Technology Object Oriented Programming

Processes. Processes (cont d)

A read or write being atomic means that its effect is as if it happens instantaneously.

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Signals. CSC209: Software Tools and Systems Programming. Furkan Alaca & Paul Vrbik

IMPLEMENTATION OF SIGNAL HANDLING. CS124 Operating Systems Fall , Lecture 15

Lecture 9: Real-Time Software Design Issues

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Exception-Handling Overview

Programming II (CS300)

ASSERTIONS AND LOGGING

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Interprocess Communication

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Programming II (CS300)

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

EXCEPTION HANDLING. Summer 2018

System Calls & Signals. CS449 Spring 2016

Exceptions, Case Study-Exception handling in C++.

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

CSci 4061 Introduction to Operating Systems. (Advanced Control Signals)

Fortran Signal Handling

Internal Classes and Exceptions

CSE 421: Introduction to Operating Systems

Programming Languages and Techniques (CIS120)

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

6.Introducing Classes 9. Exceptions

Introduction Unit 4: Input, output and exceptions

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

CSE 331 Software Design & Implementation

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 18

CSE410 Operating Systems Spring 2018 Project 1: Introduction to Unix/Linux Signals

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

C16b: Exception Handling

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process

Chapter 4 Multithreaded Programming

Exception Handling in C++

Data Structures. 02 Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Exceptions. CSC207 Winter 2017

EXCEPTIONS. Prof. Chris Jermaine

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

COMP6771 Advanced C++ Programming

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

Data Structures. Subodh Kumar. Dept of Computer Sc. & Engg. IIT Delhi

Download link: Java Exception Handling

Designing Robust Classes

COMP1008 Exceptions. Runtime Error

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers

CSC209H Lecture 8. Dan Zingaro. March 4, 2015

CPSC 427: Object-Oriented Programming

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Exceptions and assertions

2.6 Error, exception and event handling

CS240: Programming in C

COSC243 Part 2: Operating Systems

Exceptions - Example. Exceptions - Example

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch

Principles of Software Construction: Objects, Design and Concurrency. Exceptions, scope, static data and methods, and Generics.

Concurrency. Lecture 14: Concurrency & exceptions. Why concurrent subprograms? Processes and threads. Design Issues for Concurrency.

Exceptional Control Flow Exists at All Levels of a System. Systemprogrammering 2007 Föreläsning 3 Exceptional Control Flow Part II

ECF Exists at All Levels of a System Exceptional Control Flow Part II Oct. 22, 2002 Topics! Process Hierarchy! Shells! Signals!

Transcription:

COP4020 Programming Languages Exception Handling Prof. Robert van Engelen

Overview What is 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 Spring 2011 2

Defensive Programming Defensive programming is a methodology that makes programs more robust to failures Meant to increase the reliability and quality of software Writing programs while in a state of constant alert for trouble, meaning add code to check for all possible runtime failures Runtime 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 Spring 2011 3

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 Spring 2011 4

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: SIGINT interrupt program SIGFPE floating point exception SIGKILL kill program SIGBUS bus error SIGSEGV segmentation violation SIGPIPE write on pipe with no reader SIGALRM real-time timer expired COP4020 Spring 2011 5

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 trouble! COP4020 Spring 2011 6

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 Uses globals and must to check status variable after each function call COP4020 Spring 2011 7

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 Spring 2011 8

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 <setjmp.h> 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 C++ destructors of local objects won t be invoked! COP4020 Spring 2011 9

Exception Handling Implementation In most programming languages, exception handlers are attached to a specific collection of program statements that can raise exceptions 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 Spring 2011 10

Exception Handling in C++ C++ has no built-in exceptions: Exceptions are user-defined STL has some useful exceptions, I/O streams uses 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 Spring 2011 11

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 Spring 2011 12

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 catch (empty_queue) {... // handle empty queue exception here COP4020 Spring 2011 13

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 Spring 2011 14

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 Spring 2011 15

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 Spring 2011 16

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 Spring 2011 17

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 COP4020 Spring 2011 18