1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown 2004-2007)

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

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.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
16-Jun-15 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.
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.
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.
Preventing and Correcting Errors
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
Slides Credit Umair Javed LUMS Web Application Development.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
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.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
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 and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 1201 Object Oriented Programming
Java Exceptions a quick review….
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
04/14/14 Exceptions.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Exceptions 10-May-19.
Chapter 11 Exceptions Java Software Solutions
Exception Handling.
Presentation transcript:

1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown )

2 From "Testing" Lecture: Program Correctness Correctness is an important aspect of software quality. There are a number of different types of errors: ●Lexical error: using words or symbols not in the language ●Syntax error: using words or symbols in the wrong order ●Semantic error: using constructs in a meaningless way ●Run-time error: your code cannot be executed ●Logical error: your program compiles and runs, but doesn't do what it was meant to do Run-time error: your code cannot be executed int values[] = new int[10]; int pos = 20; last = values[pos];

3 Problems at Run-time ●some run-time errors are internal to your program, so one option to get rid of them is debugging your code ●Reference null pointer; index out of bounds; division by zero;... ●others arrive from external factors, and cannot be solved by debugging ●communication from an external resource – e.g. a file server or database ●clients (i.e. other programs) are not trustworthy, and supply you with faulty data

4 Defensive programming ●your code must take responsibility for protecting itself from receiving bad data or other exceptional run-time situations (e.g. network down, disk full, etc) ●you must anticipate these problems ●your code must detect these problems ●your code must respond to these problems sensibly ●but beware of making your code hard to read and code 'bloat'

5 Responding to errors with defaults ●suppose a user types something into a JTextField called tf and you expect them to type a month name...but what if they don't? ●Can validate input public String getMonthFromTF() { String str = tf.getText(); if ( ! isValidMonthName(str)) return "Jan"; else return str; } ●but now the client of the method doesn't know if the user typed "Jan" or rubbish!

6 Responding with special values ●or return a special value, e.g. -1, NULL, that signals a problem has occurred: public String getMonthFromTF() { String str = tf.getText(); if (! isValidMonthName(str)) return null; else return str; } Issues: ●special values might not always be available ●will the client remember to check for them?

7 Exception Handling I ●Java provides a systematic way of representing, transmitting, capturing and handling well-defined abnormal situations ●when the method detects the abnormal situation, it creates an object called an exception ●And throws the exception, requiring it to be caught and handled by an appropriate exception handler ●This is an abnormal return of the flow of control from the method to the client ●Handling is separated from detecting/throwing, so your code does not get polluted with detailed checks

8 Exception Handling II ●Other languages that support exception handling include.NET languages, Ada, Objective-C, and Eiffel ●PL/1 was one of first languages to employ exception handling ●Exception handling mechanism in most popular programming languages is largely similar ●Exception handling is recommended to be used only for signalling/dealing with error conditions and not the normal flow of execution

9 Implementation ●In Java exceptions (and errors) are objects ●Exceptions can be raised automatically or explicitly thrown ●Java allows multiple handlers which catch different classes of exceptions ●An alternative is to have a single handling clause which determines the class of exception internally ●finally clause to release resources (executed whether exception occurred or not) ●Terminology varies across languages ●throw or raise; catch or rescue; finally or ensure

10 Exceptions and Errors in Java ●An exception is an object that describes an unusual or erroneous situation ●An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught ●Java has a predefined set of exceptions and errors that can occur during execution ●A programmer can also define a new type of exception ●A program can deal with an exception in one of three ways: ●ignore it ●handle it where it occurs ●handle it in another place in the program

11 Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that: ●indicates the line on which the exception occurred ●shows the method call trail that lead to the attempted execution of the offending line // generates exception public class Zero { public static void main (String[] args) { int numerator = 1; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); }

12 public void method(int arg) { try { //all your normal code goes here //if something goes wrong, Java will "throw" an //Exception, and execution of this block will //stop and we move into the "catch" block } catch (Exception e) { //statement saying what to do if an abnormal //error occurred, and you can get details of //the error from the object reference "e" } Exception Handling: schematic example

13 Classes of Exceptions ●Java provides a variety of different classes describing types of exception ●Classes are arranged into a hierarchy with Exception at the top ●Different classes means that the programmer can specify different responses to different types of error ●Wrap the core code inside a try block, and immediately follow it with catch blocks for each type of Exception ●Each catch clause has an associated exception type and is called an exception handler ●When an exception occurs, processing continues at the first catch clause that matches the exception type

14 The Exception Class Hierarchy ●Classes that define exceptions are related by inheritance, forming an exception class hierarchy ●All error and exception classes are descendents of the Throwable class ●A programmer can define an exception by extending the Exception class or one of its descendants ● Exception is in the package java.lang ●The parent class used depends on how the new exception will be used

Classes of Exceptions Exception CloneNotSupportedException IOException EOFException FileNotFoundException MalformedURLException InterruptedException RuntimeException ("unchecked") IllegalArgumentException NumberFormatException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException NullPointerException

16 IOException Class Operations performed by some I/O classes may throw an IOException because a file might not exist or file exists but program may not be able to find it or the file might not contain the kind of data we expect public class TestData { public static void main (String[] args) throws IOException{ int value =5; FileWriter fw = new FileWriter (test.dat); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); for (int line=1; line <= 10; line++) { for (int num=1; num <= 10; num++) { outFile.print (value + " "); } outFile.close(); }

17 Example: Integer.parseInt ●suppose you expect the user to type an integer into a JTextField ● parseInt throws a NumberFormatException if the String it is given as input cannot be converted to an int ●the client code should catch and handle the exception: try { String str = tf.getText().trim(); int num = Integer.parseInt(str);... } catch (NumberFormatException nfe) { System.out.println("NOT AN INTEGER!"); }

18 The try block and its catch blocks try { some statements to open and read a file } catch (FileNotFoundException fnfe) { state what to do if the file didn't exist } catch (EOFException eofe) { state what to do if EOF encountered unexpectedly } ●try to execute the try block; if no exceptions are thrown, the catch blocks are ignored ●if any statement in the try block throws an exception, the rest of the try block is not executed. Java finds the appropriate catch block, and executes it instead

19 the finally block try { some statements } catch (SomeException e) { handle exception } finally { more statements } ●try to execute the try block ●if an exception is thrown, catch and handle it ●Either way, then execute the finally block

20 Which catch block is chosen? ●Java looks through the catch clauses one by one and executes the first one it finds that matches (i.e. catches the exception class or a superclass) ●why would this be silly? catch (IOException ioe) { handle the exception } catch (EOFException eofe) { handle the exception }

21 What if no catch block matches ●if no catch blocks match, Java tries to pass the exception up the call chain ●if no method in the chain catches it, Java displays an error message on the output window and terminates (except for GUIs) Java runtime system main method calls main method1 calls method1 method2 calls method2 exception if not caught

22 Throwing the exception up the chain ●if you anticipate a possible exception being thrown to a method, but you don't want the method to handle it, throw it explicitly in the method signature public void process() throws IOException { ●if you detect an error, and want some calling method to handle it, explicitly throw a new Exception public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException();...

23 throw Example A throw statement can be executed inside an if statement that evaluates a condition to see if the exception should be thrown The following snippet of code throws a Exception defined below: OutOfRangeException problem = new OutOfRangeException ("Input out of range"); System.out.print ("Enter integer between " + MIN + " and " + MAX); int value = scan.nextInt(); if (value MAX) throw problem; public class OutOfRangeException extends Exception { OutOfRangeException (String message) { super (message); }

24 Checked Exceptions ●An exception is either checked or unchecked ●A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it ●A throws clause is appended to the method header/signature, e.g. void read(String fname) throws IOException, ClassNotFoundException ●The compiler will issue an error if a checked exception is not caught or asserted in a throws clause ●Note that Java is unusual in having checked exceptions (other languages CLU, Modula 3)

25 Unchecked Exceptions ●some Exceptions are not required to be caught ●The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants ●Runtime exceptions could occur in many areas of the code, and requiring that each possible location has a handler will produce inefficient code ●therefore Java allows runtime exceptions to be generated, but does not insist that you catch them