241-211 OOP (Java): Exceptions/15 1 241-211. OOP Objectives – –examine Java's exception handling Semester 2, 2013-2014 15. Exceptions.

Slides:



Advertisements
Similar presentations
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
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.
Outline DivideByZeroTes t.java 1 // Fig. 15.1: DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*;
COMP 121 Week 5: Exceptions and Exception Handling.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Handling errors Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
11-Jun-15 Exceptions. 2 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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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. 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.
Handling errors Writing robust code. 16/12/2004Lecture 10: Handling Errors2 Main concepts to be covered Defensive programming. –Anticipating that things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
Handling errors Exception handling and throwing Simple file processing.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Objects First With Java A Practical Introduction Using BlueJ Handling errors 1.0.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
COS 260 DAY 27 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Chapter 15 – Exception Handling
Presentation transcript:

OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions

OOP (Java): Exceptions/15 2 Contents 1.Motivation 2.Exception Handling (in outline) 3.Many Catch Blocks 4.The Exception Class Hierarchy 5.Throwing an Exception continued

OOP (Java): Exceptions/ Not Handling an Exception 7.Defining New Exceptions 8.Nested Catching 9. What if Several Handlers can match? 10.The finally Clause 11.The assert Statement

OOP (Java): Exceptions/ Motivation Lots of error checking in code makes the code harder to understand – –more complex – –more likely that the code will have errors! Add error checking to the following C code: int a[SIZE]; y =... x = (1.0/a[y]) + (2.0/a[y+1]) + (3.0/a[y+2]);

OOP (Java): Exceptions/15 5 Some Error Checking (in C)! : if (y >= SIZE) printf(“Array index %d too big\n”, y); else if (a[y] == 0) printf(“First denominator is 0\n”); if (y+1 >= SIZE) printf(“Array index %d too big\n”, y+1); else if (a[y+1] == 0) printf(“Second denominator is 0\n”); if (y+2 >= SIZE) printf(“Array index %d too big\n”, y+2); else if (a[y+2] == 0) printf(“Third denominator is 0\n”); :

OOP (Java): Exceptions/15 6 A Solution Separate the error checking code from the main program code – –the standard approach since the 1980’s Java uses exception handling – –a mechanism that it “borrowed” from C++ and Ada

OOP (Java): Exceptions/ Exception Handling (in outline) Format of code: statements; try { code...; } catch (Exception-type e) { code for dealing with e exception } more-statements; a try block a catch block

OOP (Java): Exceptions/15 8 Basic Approach The programmer wraps the error-prone code inside a try block. If an exception occurs anywhere in the code inside the try block, the catch block is executed immediately – –the block can use information stored in the e object continued

OOP (Java): Exceptions/15 9 After the catch block (the catch handler) has finished, execution continues after the catch block (in more-statements ). – –execution does not return to the try block continued

OOP (Java): Exceptions/15 10 If the try block finishes successfully without causing an exception, then execution skips to the code after the catch block – –i.e. to more-statements

OOP (Java): Exceptions/15 11 Catching Math Errors int x = 0; int y; : try { y = 1/x; : } catch (ArithmeticException e) { System.out.println(e);...; y = 0; } System.out.println(“y is “ + y); any Java code is allowed here

OOP (Java): Exceptions/15 12 Attempting Recovery // Try to save an address book boolean successful = false; int attempts = 0; do { try { addressbook.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println( e.getMessage() ); System.out.println("Unable to save to " + filename); attempts++; if(attempts < MAX_ATTEMPTS) filename = an alternative file name; } } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) Report the problem and give up;

OOP (Java): Exceptions/ Many Catch Blocks There can be many catch blocks associated with a try block – –the choice of which to use is based on matching the exception object (e) with the argument type of each catch block – –after a catch handler has finished, execution continues after all the handlers

OOP (Java): Exceptions/15 14 Code Format statements; try { code...; } catch (NullPointerException e) { code for dealing with a NULL pointer exception } catch (IOException e) { code for dealing with an IO exception } catch (MyOwnException e) { code for dealing with a user-defined exception } more-statements;

OOP (Java): Exceptions/ The Exception Class Hierarchy for errors that occur inside the JVM, not in your code

OOP (Java): Exceptions/15 16 In More Detail (but not all!)

OOP (Java): Exceptions/ Two Exception Categories 1. Checked exceptions – –subclasses of Exception – –recovery should be possible for these types of errors – –your code must include try-catch blocks for these or the compiler will reject your program e.g. IOException continued

OOP (Java): Exceptions/ Unchecked exceptions – –subclasses of RuntimeException – –exceptions of this type usually mean that your program should terminate – –the compiler does not force you to include try- catch blocks for these kinds of exceptions e.g. ArithmeticException

OOP (Java): Exceptions/ Text IO IO can generate lots of exceptions, but usually the program can recover – –e.g. file not found, so look somewhere else Most IO methods can produce java.io.IOException – –a checked exception which your code must handle with try-catch blocks Uses checked exceptions 1 1

OOP (Java): Exceptions/15 20 Text Output to a File Use the FileWriter class – –open a file – –write to the file – –close the file Failure at any point results in an IOException

OOP (Java): Exceptions/15 21 Text Output to File try { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) {... writer.write(next piece of text);... } writer.close(); } catch(IOException e) { // something went wrong with accessing the file } the try-catch block must be included

OOP (Java): Exceptions/15 22 Text Input From File Use the FileReader class. Use BufferedReader for line-based input: – –open a file – –read from the file – –close the file Failure at any point results in an IOException.

OOP (Java): Exceptions/15 23 Text Input From File try { BufferedReader reader = new BufferedReader(new FileReader("filename")); String line = reader.readLine(); while(line != null) { do something with line line = reader.readLine(); } reader.close(); } catch(FileNotFoundException e) { // the specified file could not be found } catch(IOException e) { // something went wrong with reading or closing } the try-catch block must be included

OOP (Java): Exceptions/ Checking Maths int x = 0; int y; : try { y = 1/x; : } catch (ArithmeticException e) {...; y = 0; } System.out.println(“y is “ + y); Uses an unchecked exception 2 2

OOP (Java): Exceptions/15 25 int x = 0; int y; : y = 1/x; : System.out.println(“y is “ + y); a try-catch block does not need to be included Or:

OOP (Java): Exceptions/ Throwing an Exception Exceptions are caused (thrown or raised) by the JVM. Also, the programmer can throw an exception by using: throw e

OOP (Java): Exceptions/15 27 Example private double safeSqrt(double x) { try { if (x < 0.0) throw new ArithmeticException();...; } catch (ArithmeticException e) { x = 0.0; }... ; return sqrt(x); }

OOP (Java): Exceptions/15 28 Exceptions thrown by a method can be either: – –caught by the method’s catch handler(s) we’ve seen examples already – –or be listed in the method's throws declaration 5.1. Handling Exceptions

OOP (Java): Exceptions/15 29 Throws Declaration Format: int g(int h) throws a, b, c { // method body which may throw // exceptions a, b, c } The idea is that the exceptions are to be passed up to the method that called g(). continued

OOP (Java): Exceptions/15 30 Example double safeSqrt(double x) throws ArithmeticException { if (x < 0.0) throw new ArithmeticException();...; return sqrt(x); }

OOP (Java): Exceptions/15 31 void foo(double x) { double result; try { result = safeSqrt(x); } catch(ArithmeticException e) { System.out.println(e); result = -1; } System.out.println("result: " + result); } foo() safeSqrt() calls throws (or returns)

OOP (Java): Exceptions/ Not Handling an Exception If a method raises an exception and it does not have a catch block or throws declaration then… – –if the exception is a runtime exception (an unchecked exception), then the program will terminate at runtime – –if the exception is a checked exception, then the compiler will reject your code at compile time

OOP (Java): Exceptions/ Defining New Exceptions You can subclass RuntimeException to create new kinds of unchecked exceptions. Or subclass Exception for new kinds of checked exceptions. Why? To improve error reporting in your program.

OOP (Java): Exceptions/ DivisionByZero Example A new unchecked maths exception: – –DivideByZeroException – –to handle division-by-zero exceptions The example program takes two strings as input, converts them to integers, and divides them – –number format exceptions are possible, and division-by-zero

OOP (Java): Exceptions/15 35 Usage continued 1. Number Format Exception There are two possible kinds of exceptions.

OOP (Java): Exceptions/15 36 continued 2. Divide By Zero Exception

OOP (Java): Exceptions/15 37 Correct at last!!

OOP (Java): Exceptions/15 38 DivideByZeroException Class public class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super( "Attempted to divide by zero" ); } }

OOP (Java): Exceptions/15 39 DivideByZeroTest.java // divide two input strings import java.text.DecimalFormat; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DivideByZeroTest extends JFrame implements ActionListener { private JTextField input1, input2, output; private int number1, number2; private double result; :

OOP (Java): Exceptions/15 40 public DivideByZeroTest() { super( "Demonstrating Exceptions" ); Container c = getContentPane(); c.setLayout( new GridLayout(3,2) ); c.add( new JLabel( "Enter numerator ", SwingConstants.RIGHT ) ); input1 = new JTextField(10); c.add( input1); :

OOP (Java): Exceptions/15 41 c.add( new JLabel( "Enter denominator and press Enter ", SwingConstants.RIGHT ) ); input2 = new JTextField(10); c.add( input2 ); input2.addActionListener(this); c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) ); output = new JTextField(); c.add( output ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setSize(425,100); setVisible(true); } // end of DivideByZeroTest()

OOP (Java): Exceptions/15 42 public void actionPerformed( ActionEvent e ) { DecimalFormat precision3 = new DecimalFormat( "0.000"); output.setText( "" ); // empty JTextField try { number1 = Integer.parseInt(input1.getText()); number2 = Integer.parseInt(input2.getText()); result = quotient( number1, number2); output.setText( precision3.format(result) ); } :

OOP (Java): Exceptions/15 43 catch ( NumberFormatException nfe ) { JOptionPane.showMessageDialog( this, "You must enter two integers", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); } catch ( DivideByZeroException dbze ) { JOptionPane.showMessageDialog( this, dbze.toString(), "Attempted to Divide by Zero", JOptionPane.ERROR_MESSAGE ); } } // end of actionPerformed() continued

OOP (Java): Exceptions/15 44 // Throw an exception when divide-by-zero public double quotient( int numerator, int denominator ) throws DivideByZeroException { if ( denominator == 0 ) throw new DivideByZeroException(); // not caught here, so listed in throws return ( double ) numerator/denominator; } // end of quotient()

OOP (Java): Exceptions/15 45 public static void main( String args[] ) { new DivideByZeroTest(); } } // end of DivideByZeroTest class

OOP (Java): Exceptions/15 46 Catching Pattern : try{ // parsing // call to quotient() } catch NumberFormat catch DivideByZero : actionPerformed() if (denom == 0) throw DivideByZero : quotient() throws... sometimes called nested catching

OOP (Java): Exceptions/ Nested Catching When an exception is thrown, its type is matched against the arguments of the catch handlers in its block. If no handler matches in that block, then the exception is passed out to the enclosing block: – –e.g. quotient() → actionPerformed() continued

OOP (Java): Exceptions/15 48 The exception keeps being passed out to the next enclosing block until: – –a suitable handler is found; or – –there are no blocks left to try and the program terminates with a stack trace

OOP (Java): Exceptions/15 49 Stack Trace Example If no handler is called, then the system prints a stack trace as the program terminates – –it is a list of the called methods that are waiting to return when the exception occurred – –very useful for debugging/testing The stack trace can be printed by calling printStackTrace()

OOP (Java): Exceptions/15 50 Using a Stack Trace // The getMessage and printStackTrace methods public class UsingStackTrace { public static void main( String args[] ) { try { method1(); } catch ( Exception e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); } } // end of main()

OOP (Java): Exceptions/15 51 public static void method1() throws Exception { method2(); } public static void method2() throws Exception { method3(); } public static void method3() throws Exception { throw new Exception( "Exception thrown in method3" ); } } // end of UsingStackTrace class

OOP (Java): Exceptions/15 52 Usage main() method1() method2() method3() Exception!! e.getMessage() output e.printStackTrace() output

OOP (Java): Exceptions/15 53 method1() and method2() require throws declarations since they call a method that may throw a Exception. The compiler will reject the program at compile time if the throws are not included – –Exception is a non-runtime (checked) exception Notes

OOP (Java): Exceptions/ What if Several Handlers can Match? If several handlers can match an exception, then the first one found by the JVM is used.

OOP (Java): Exceptions/15 55 What is a Match? Matching is based on the Exception class hierarchy. If the class of the exception is the same as the argument type of the handler, then there is a match. continued

OOP (Java): Exceptions/15 56 A match is also possible if the handler argument is a superclass for the exception type. – –e.g. the handler: catch(ArithmeticException e) { // code } – –can catch an exception of class DivisionByZeroException continued

OOP (Java): Exceptions/15 57 The most general handler: catch (Exception e) { // code } – –can catch any exception because Exception is the superclass of all exception types

OOP (Java): Exceptions/ The finally Clause try { // Protect one or more statements here. } catch(Exception e) { // Report and recover from the exception here. } finally { // Perform actions here whether // or not an exception is thrown. }

OOP (Java): Exceptions/15 59 A finally clause is executed even if a return statement is executed in the try or catch clauses. An uncaught or nested exception still exits via the finally clause. Typical usage is to free system resources before returning, even after throwing an exception – –e.g. close files, network links

OOP (Java): Exceptions/ The assert Statement Used for internal consistency checks – –e.g. check an object's state after it was meant to have been changed Use asserts during development, and remove them in the finished version of the program.

OOP (Java): Exceptions/15 61 Two forms: – –assert boolean-expression – –assert boolean-expression : msg-expr boolean-expression should be true at this point in the execution. An AssertionError is thrown if the boolean- expression is false, and msg-expr is output. Format

OOP (Java): Exceptions/15 62 Assert Statement public void removeDetails(String key) { if(key == null) throw new IllegalArgumentException("..."); if(keyInUse(key)) { ContactDetails details = book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; } assert !keyInUse(key); assert consistentSize() : "Inconsistent book size in removeDetails"; }

OOP (Java): Exceptions/15 63 Guidelines for Asserts Use them for checking your code only. Remove them from your finished code. Don’t change things in asserts: // BAD: assert book.remove(name); This is bad because asserts should only check things.