Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
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.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
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.
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Chapter 9 Exception Handling Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exception handling Dealing with life’s little surprises.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
CS102--Object Oriented Programming Lecture 11: Exception Handling Copyright © 2008 Xiaoyan Li.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Software Solutions Foundations of Program Design Sixth Edition
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Chapter 5 Loops.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
COMP Exception Handling Yi Hong June 10, 2015.
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.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Exception Handling Chapter 9.
Exceptions & exception handling
Exceptions & exception handling
Exception Handling.
Fundamental Error Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Chapter 9 Exception Handling
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 12 Exception Handling and Text IO Part 1
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3. Throw an exception. 4. Declare that an exception may be thrown (in a particular function). 5. Handle the possibility that an exception may be thrown.

1. Define a new exception class extend Exception (or extend a subclass of Exception) See tion.html. tion.html This creates a new type. All have a ctor w/ a single String arg. Each has an accessor method called getMessage() that returns the String from the ctor arg.

Define a new exception class example //typical sample code public class DivisionByZeroException extends Exception { public DivisionByZeroException ( ) { super( “Division by zero!” ); } public DivisionByZeroException ( String message ) { super( message ); }

Define a new exception class example (w/ more information) public class BadNumberException extends Exception { private int mBadNumber; public BadNumberException ( ) { super( “BadNumberException” ); } public BadNumberException ( String message ) { super( message ); } public BadNumberException ( int number ) { super( “BadNumberException” ); mBadNumber = number; } public int getBadNumber ( ) { return mBadNumber; }

2. Create an exception instance Ex. new Exception( “Uh oh!” ); Exception e = new Exception( “Rats!” );

3. Throw an exception Ex. throw new Exception( “Invalid value.” ); Exception e = new Exception( “Invalid age.” ); throw e;

4. Declare (a method that indicates) that an exception may be thrown Ex. public int f ( int x ) throws Exception { … }

5. Handle the possibility that an exception may be thrown The try-catch blocks: try { … } catch (Exception e) { … }

Exercises 1. What is the output produced by the following code? int waitTime = 46; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 2. What is the output produced by the following code? int waitTime = 12 ; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 3. What are the throw statements (below)? int waitTime = 12 ; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 4. What happens when a throw statement is executed? This is a general question. Tell what happens in general, not simply what happens in the code below or some other sample code. int waitTime = 12; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 5. What is the try block (below)? int waitTime = 12 ; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 6. What is the catch block (below)? int waitTime = 12 ; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 7. What is the catch block parameter (below)? int waitTime = 12 ; try { System.out.println( “Try block entered.” ); if (waitTime>30) throw new Exception( “Over 30.” ); else if (waitTime<30) throw new Exception( “Under 30.” ); else System.out.println( “No exception.” ); System.out.println( “Leaving try block.” ); } catch (Exception thrownObject) { System.out.println( thrownObject.getMessage() ); } System.out.println( “After catch block.” );

Exercises 8. Is the following legal? Exception exceptionObject = new Exception( “Oops!” );

Exercises 9. Is the following legal? Exception exceptionObject = new Exception( “Oops!” ); throw exceptionObject;

Try-catch blocks examples Recall the Integer class (see ger.html). ger.html What method do we use to convert a String into an int? What happens if the String does not contain an int? Try it. What happens when we walk off of the end of an array? Can you avoid this behavior?

Useful exception subclasses ArrayIndexOutOfBoundsException NumberFormatException IOException NoSuchMethodException FileNotFoundException

Exercises 10. Define an exception class called PowerFailureException. The class should have a ctor w/ no parameters. If an exception is thrown with this zero-argument ctor, getMessage should return “Power Failure!” The class should also have a ctor w/ a single parameter of type String. If an exception is thrown w/ this ctor, then getMessage returns the value that was used as an argument to the ctor.

Exercises 11. Define an exception class called TooMuchStuffException. The class should have a ctor w/ no parameters. If an exception is thrown with this zero-argument ctor, getMessage should return “Too much stuff!” The class should also have a ctor w/ a single parameter of type String. If an exception is thrown w/ this ctor, then getMessage returns the value that was used as an argument to the ctor.

Exercises 12. Suppose the exception class ExerciseException is defined as follows: public class ExerciseException extends Exception { public ExerciseException ( ) { super("Exercise Exception thrown!"); System.out.println("Exception thrown."); } public ExerciseException ( String message ) { super(message); System.out.println( "ExerciseException invoked with an argument."); } What output would be produced by the following code (which is just an exercise and not likely to occur in a program)? ExerciseException e = new ExerciseException( “Do be do” ); System.out.println( e.getMessage() );

Exercises 14. Suppose the exception class MyException is defined as follows: public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); } public MyException ( String message ) { super("MyException: " + message); } What output would be produced by the following code? int number; try { System.out.println( “try block entered” ); number = 42; if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” ); } catch (MyException exceptionObject) { System.out.println( exceptionObject.getMessage() ); } System.out.println( “end of example.” );

Exercises 15. Suppose the exception class MyException is defined as follows: public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); } public MyException ( String message ) { super("MyException: " + message); } What output would be produced by the following code? int number; try { System.out.println( “try block entered” ); number = 42; if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” ); } catch (Exception exceptionObject) { //was MyException System.out.println( exceptionObject.getMessage() ); } System.out.println( “end of example.” );

Exercises 16. Suppose the exception class MyException is defined as follows: public class MyException extends Exception { public MyException ( ) { super("My Exception thrown!"); } public MyException ( String message ) { super("MyException: " + message); } What output would be produced by the following code? int number; try { System.out.println( “try block entered” ); number = -58; //was 42 if (number>0) throw new MyException( “Hi Mom!” ); System.out.println( “leaving try block” ); } catch (MyException exceptionObject) { System.out.println( exceptionObject.getMessage() ); } System.out.println( “end of example.” );

Multiple catch blocks More general form of try-catch blocks: try { … } catch (NegativeNumberException e) { … } catch (DivisionByZeroException e) { … } The order of catch blocks is important as they are evaluated in sequence. So put most specific first.

Exercises 19. What output will be produced by the following code? public class NegativeNumberException extends Exception { public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); } public NegativeNumberException ( String message ) { super( message ); } int n; try { n = 42; if (n > 0) throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println( “bingo!” ); } catch (NegativeNumberException e) { System.out.println( “first catch” ); } catch (Exception e) { System.out.println( “second catch” ); } System.out.println( “end of exercise” );

Exercises 20. What output will be produced by the following code? public class NegativeNumberException extends Exception { public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); } public NegativeNumberException ( String message ) { super( message ); } int n; try { n = -42; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println( “bingo!” ); } catch (NegativeNumberException e) { System.out.println( “first catch” ); } catch (Exception e) { System.out.println( “second catch” ); } System.out.println( “end of exercise” );

Exercises 21. What output will be produced by the following code? public class NegativeNumberException extends Exception { public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); } public NegativeNumberException ( String message ) { super( message ); } int n; try { n = 0; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println( “bingo!” ); } catch (NegativeNumberException e) { System.out.println( “first catch” ); } catch (Exception e) { System.out.println( “second catch” ); } System.out.println( “end of exercise” );

Exercises What output will be produced by the following code? public class NegativeNumberException extends Exception { public NegativeNumberException ( ) { super( "Negative Number Exception!“ ); } public NegativeNumberException ( String message ) { super( message ); } int n; try { n = -42; //was 42 if (n > 0) throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println( “bingo!” ); } catch (Exception e) { System.out.println( “first catch” ); } catch (NegativeNumberException e) { System.out.println( “second catch” ); } System.out.println( “end of exercise” );

Throwing exceptions in methods Methods can throw exceptions, and/or call methods that throw exceptions. Catch or declare rule: Such a method must then contain a try-catch block (already discussed), and/or the function heading must specify that the method may throw an exception. The catch or declare rule is not always enforced. 1. Checked exceptions (descendents of Exception) 2. Unchecked exceptions (descendents of RuntimeException)

Declare (a method that indicates) that an exception may be thrown Ex. public int f ( int x ) throws Exception { … } public boolean g ( ) throws DivideByZeroException, SomeOtherException { … }

Useful methods that may throw exceptions What method can be used to convert strings to integers? Open a file for reading (see putStream.html) putStream.html The Scanner class (see ner.html#nextInt()) ner.html#nextInt()

finally clause Most general form of try-catch-finally blocks: try { … } catch (ExceptionClass 1 e) { … } catch (ExceptionClass 2 e) { … } catch (ExceptionClass n e) { … } finally { //code executed whether or not an exception was thrown … }

finally clause Three cases: 1. no exception occurs in the try block 2. an exception occurs in the try block and is caught 3. an exception occurs in the try block but doesn’t match any catch

Exercises public class FinallyDemo { public static void main ( String[] args ) { try { exerciseMethod( 42 ); } catch(Exception e) { System.out.println( "Caught in main.“ ); } public static void exerciseMethod ( int n ) throws Exception { try { if (n > 0) throw new Exception( ); else if (n < 0) throw new NegativeNumberException( ); else System.out.println( "No Exception." ); System.out.println( "Still in sampleMethod." ); } catch (NegativeNumberException e) { System.out.println( "Caught in sampleMethod." ); } finally { System.out.println( "In finally block." ); } System.out.println( "After finally block." ); } 29. What is the output of the following program? What would be the output if the argument to exerciseMethod was -42 instead of 42. How about 0?

Exercises 22. What is the output produced by the following program? public class Exercise { public static void main ( String[] args ) { try { System.out.println( "Trying" ); sampleMethod( 98.6 ); System.out.println( "Trying after call." ); } catch(Exception e) { System.out.println( "Catching." ); } System.out.println( "End program." ); } public static void sampleMethod ( double test ) throws Exception { System.out.println( "Starting sampleMethod." ); if (test < 100) throw new Exception( ); }

Exercises 23. What is the output produced by the following program? public class Exercise { public static void main ( String[] args ) { try { System.out.println( "Trying" ); sampleMethod( 212 ); //was 98.6 System.out.println( "Trying after call." ); } catch(Exception e) { System.out.println( "Catching." ); } System.out.println( "End program." ); } public static void sampleMethod ( double test ) throws Exception { System.out.println( "Starting sampleMethod." ); if (test < 100) throw new Exception( ); }

Exercises 24. Correct the following method definition by adding a suitable throws clause: public static void doStuff ( int n ) { if (n<0) throw new Exception( “Negative number.” ); } 25. What happens if an exception is thrown inside a method invocation but the exception is not caught inside the method?

Exercises 30. What is the output of the following? import java.util.Scanner; import java.util.InputMismatchException; public class InputMismatchExceptionDemo { public static void main ( String[] args ) { Scanner keyboard = new Scanner( System.in ); int number = 0; //to keep compiler happy boolean done = false; while (! done) { try { System.out.println( "Enter a whole number:" ); number = keyboard.nextInt(); done = true; } catch (InputMismatchException e) { keyboard.nextLine(); System.out.println( "Not a correctly written whole number.“ ); System.out.println( "Try again. " ); } System.out.println( "You entered " + number ); }

Exercises import java.util.Scanner; import java.util.InputMismatchException; public class InputMismatchExceptionDemo { public static void main ( String[] args ) { Scanner keyboard = new Scanner( System.in ); int number = 0; //to keep compiler happy boolean done = false; while (! done) { try { System.out.println( "Enter a whole number:" ); number = keyboard.nextInt(); done = true; } catch (InputMismatchException e) { keyboard.nextLine(); System.out.print( "Not a correctly written “); System.out.println( “whole number.“ ); System.out.println( "Try again. " ); } System.out.println( "You entered " + number ); } 31. Give the definition for the following method. Use code similar to this code. /** Precondition: keyboard is an object of the class Scanner that has been set up for keyboard input (as we have been doing right along). Returns: An int value entered at the keyboard. If the user enters an incorrectly formed input she or he is prompted to reenter the value. */

9-43 /** Chapter 9 question 1 * Question1Average.java * * This program calculates the average of N numbers and throws * an exception if a negative number is entered for N. If any * exception occurs while entering a number, the user will be prompted * for the number again. * */ import java.util.Scanner; public class Question1Average { public static void main(String[] args) { // Variable declarations Scanner scan = new Scanner(System.in); int n = 0; int sum = 0; double average; boolean error;

9-44 // Loop until there is no error do { try { error = false;// Assume no error System.out.println("How many numbers do you want to enter?"); n = scan.nextInt(); if (n <= 0 ) throw new Exception("Number must be greater than 0."); } //end try catch (Exception e)// Catch any exception and print { // the error message error = true; System.out.println(e.getMessage()); } //end catch } while (error);

9-45 // Loop through each number and calculate the average for (int i=0; i<n; i++) { // Repeat input as long as there is an error do { try { error = false;// Assume no error System.out.println("Enter number " + (i+1)); int num = scan.nextInt(); sum += num; } catch (Exception e) { // Set error flag if an exception occurs error = true; System.out.println("Error, please enter the number again."); // Read newLine remaining from nextInt String temp = scan.nextLine(); } } while (error); }// end for average = (double) sum / n; System.out.println("\nThe average is " + average); } //end main } // Question1Average