Defensive Programming

Similar documents
COP4020 Programming Languages. Exception Handling Prof. Robert van Engelen

14. Exception Handling

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

Chapter 14. Exception Handling and Event Handling

Sri Vidya College of Engineering & Technology Question Bank

Chapter 14. Exception Handling and Event Handling ISBN

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

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

G Programming Languages - Fall 2012

EXCEPTION HANDLING. Summer 2018

2.6 Error, exception and event handling

Download link: Java Exception Handling

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

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

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Java Loose Ends. 11 December 2017 OSU CSE 1

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

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

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

Exception-Handling Overview

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

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

COMP1008 Exceptions. Runtime Error

More on Objects in JAVA TM

6.Introducing Classes 9. Exceptions

Fundamentals of Object Oriented Programming

Errors and Exceptions

Assertions and Exceptions Lecture 11 Fall 2005

Introduction Unit 4: Input, output and exceptions

C16b: Exception Handling

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

Compiling and Interpreting Programming. Overview of Compilers and Interpreters

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Exceptions. CSC207 Winter 2017

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

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

Object Oriented Programming

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

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

Programming II (CS300)

Internal Classes and Exceptions

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

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

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

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

ECE 122. Engineering Problem Solving with Java

16-Dec-10. Consider the following method:

About this exam review

CPSC 427: Object-Oriented Programming

Control Abstraction. Hwansoo Han

Programming Languages and Techniques (CIS120)

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

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

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

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

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Data Structure. Recitation IV

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Program Correctness and Efficiency. Chapter 2

Correctness and Robustness

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Data Structures. 02 Exception Handling

Exceptions. Gunnar Gotshalks EX 1

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

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

CS112 Lecture: Exceptions and Assertions

Overview. finally and resource cleanup

CSE 143 Java. Exceptions 1/25/

2IP15 Programming Methods

COP4020 Fall 2006 Final Exam

Lecture 19 Programming Exceptions CSE11 Fall 2013

CSE 331 Software Design & Implementation

Error Management in Compilers and Run-time Systems

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

Chapter 13 Exception Handling

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

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

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

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

9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation

Exceptions and assertions

Java Errors and Exceptions. Because Murphy s Law never fails

What can go wrong in a Java program while running?

Object Oriented Software Design

Introduction to Java Written by John Bell for CS 342, Spring 2018

Object Oriented Software Design

CSCI 261 Computer Science II

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

Lecture 9: Control Flow

Engineering Robust Server Software

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

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

G Programming Languages - Fall 2012

Transcription:

Copyright R.A. van Engelen, FSU Department of Computer Science, 2000 Exception Handling In this set of notes you will learn about: Defensive programming Ways to catch and handle run-time errors without exception handling Exception handling in C++ Exception handling in Java Note: These notes cover Section 8.5 of the textbook, upto and including 8.5.2. Helpful extra hand-out material is available in class. Defensive Programming Defensive programming is a technique that makes programs more robust to unexpected events such as run-time errors Less program "crashes" at run time increases the quality o software Unexpected events may occur due to Erroneous user input (e.g. entering a date in the wrong format) File input and output problems (e.g. end of file or disk ful Problems with arithmetic (e.g. overflow) Hardware and software interrupts (e.g. hitting the break k Programming language implementation of exception handling can make defensive programming easier An exception is a special unexpected error condition at ru time Built-in exceptions may be detected automatically by the language implementation Exceptions can be explicitly raised Exceptions are handled by exception handlers to recover from error conditions. Exception handlers are user-defined program fragments th are executed when an exception is raised

Catching Run-Time Errors Without Exception Handling C, Fortran 77, and Pascal do not support exception handling Other ways of catching and handling run-time errors have to be invented when a language does not support exception handling Adds "clutter" that obscures a program Method 1: Functions can 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! Catching Run-Time Errors without Exception Handling (cont d) Method 2: Functions and procedures can set status values 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 Need to check status value after each function call Method 3: Pass an error-handling procedure to a subroutine Example in C: int somefun(file *fd, void handler(int)) { if (feof(fd)) handler(-1); // error detected return value; // return a value

Exception Handlers Purposes of an exception handler: 1. Recover from an exception to safely continue execution 2. If full recovery is not possible, print error message(s) 3. If the exception cannot be handled locally, clean up local resources and reraise the exception to propagate it to another handler In most languages, exception handlers can be attached to a collection of program statements When an exception occurs in the collection of statements, a handler is selected 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 When propagating the unhandled exception to the caller, the current subroutine is cleaned up: subroutine frames are removed and destructor functions are called to remove objects Exception Handling in C++ No built-in exceptions: Exceptions are user defined Exceptions have to be explicitly raised by throw An exception is a type or 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 throw a "short int" exception Exception handlers are attached to a collection of statements using try-catch: throw eof_condition; // matches short int exception throw empty_queue(myq); throw 6; // matches int exception catch (short int) { // handle end of file catch (empty_queue e) { // handle empty queue, where e is an empty_queue object catch (int n) { // handle exception of type int, where n contains number catch () { // catch-all handler

Exception Handling in C++ (cont d) A catch-block is executed that matches the type/class of the throw parameter A catch specifies a type/class and an optional parameter that is the object passed by throw to the catch just like call-by-value parameter passing, where the parameter has a local scope in the catch-block An optional catch() with ellipsis catches all remaining exceptions that do not have a matching handler After an exception is handled in a catch-block, execution continues with statements after the try-catch construct and all dynamic variables allocated in the try-block before the throw are deallocated If no handler matches a throw (and there is no catch with ellipsis), the current function is terminated and the exception is propagated to the caller of the function afun(); // may throw empty queue exception catch (empty_queue) { // handle empty queue exception (this example passes no empty_queue object) Functions can list the types of exceptions it can raise int afun() throw (int, empty_queue) { where afun can raise int and empty_queue exceptions, as well as subclasses of empty_queue Exception Handling in Java All Java exceptions are objects of classes that are descendant class Throwable Classes Error and Exception are descendants of Throwable Error: Java built-in interpreter exceptions such as "out of memory" Exception: user-defined exception classes are subclasses Exception RuntimeException for dynamic semantic errors and IOException for I/O exceptions are predefined descendan of Exception Example user-defined exception declared as a descendant of Exception: class MyException extends Exception { public MyException() {; public MyException(String msg) { super(msg); // let class Exception handle the mess An exception is raised by throw: throw new MyException(); throw new MyException("some specific error message"); MyException e = new MyException(); throw e;

Exception Handling in Java (cont d) The syntax of the try-catch handlers in Java are the same as C++ try-catch also has an optional finally block catch (MyException e) { // catch exceptions that are (descendants of) MyException catch (Exception e) { // catch-all handler: all exceptions are descendants of Exception finally { // always executed for user-defined clean-up operations The finally block is always executed even when a break or return statement appears in the protected try-block A handler of 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 after the try-catch construct and all dynamic variables allocated in the try-block before the throw are deallocated If no handler matches a throw, the current function is terminated and the exception is propagated to the caller of the function Exception Handling in Java (cont d) Java methods must list the exceptions that it can raise A list of exceptions a method can raise is given using the thr keyword class GradeList { int newgrade; void BuildDist() throws IOException { // I/O operations that may raise IOException The Java compiler will verify the list of exceptions for completeness Exception classes Error and RuntimeException and their descendants are unchecked exceptions and not verified by the compiler There are no default exception handlers or catch-all handlers For a catch-all: Exception catches Exception and all its descendants