Throwing, Catching Defining

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
COMP 121 Week 5: Exceptions and Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
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.
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.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 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.
CS1020 Data Structures and Algorithms I Lecture Note #6 Exceptions Handling exceptional events.
CS1101: Programming Methodology Aaron Tan.
Preventing and Correcting Errors
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Chapter 8-Exception Handling/ Robust Programming.
(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 an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
Exceptions Chapter 9.
Exceptions: When things go wrong
Recitation 2 Exception handling.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
Chapter 9 Exception Handling
Creating and Modifying Text part 2
Chapter 12 Exception Handling and Text IO
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
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.
Exceptions & exception handling
Exceptions & exception handling
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Exception Handling and Reading / Writing Files
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CSE 143 Java Exceptions 1/18/2019.
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
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.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exceptions Review Checked Vs. Unchecked Exceptions
Presentation transcript:

Throwing, Catching Defining Exceptions Throwing, Catching Defining

Outcomes Find the exception that crashed a program find where it happened in your code Write a try-catch block to catch exceptions your program might throw Design and place try-catch blocks so your program recovers gracefully Create your own Exception class

Exceptional Circumstances Reading numbers from user User types in a word not the sort of thing we expected program crashes Enter a number: 20 Enter another number: done Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) see SumNumbers.java

Exceptional Circumstances Reading file name from user User gives name of a file that doesn’t exist can’t open that file for input program crashes Enter the name of a file and I will sum its numbers: noSuchFile.txt Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20) see SumUsersFile.java

Exceptions Our Scanner has thrown an exception Exception in thread “main” java.util.InputMismatchException Exception in thread “main” java.io.FileNotFoundException It ran into an error it couldn’t fix program “crashed” eventually!

What Exception? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

Where? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

Where??? Methods call other methods One method throws the exception which may call other methods in turn One method throws the exception error message shows whole “stack” of calls main nextDouble Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) next throwFor

Look for Your Program Many of the methods don’t belong to you you can’t do anything about them Some of the methods are yours that’s where you can do something line 26 of SumNumbers.java Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26)

Exercise Where did this exception get thrown from? What methods were called? What line(s) of your program are relevant? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at csci1227.Scanner.nextInt(Scanner.java:169) at ArraySearcher.search(ArraySearcher.java:178) at ArraySearcher.main(ArraySearcher.java:58)

Exception Hierarchy Exception IOException RuntimeException EOFException ClassCastException FileNotFoundException ConcurrentModificationException IndexOutOfBoundsException IllegalArgumentException ArrayIndexOutOfBoundsException NoSuchElementException StringIndexOutOfBoundsException NullPointerException InputMismatchException

Throwing Exceptions Throw an exception when errors happen and you can’t deal with it properly Throw an appropriate type of exception illegal argument  IllegalArgumentException out of bounds  IndexOutOfBoundsException bad time for request  IllegalStateException If necessary, make your own exception type extend RuntimeException

Setters Throwing Exceptions Client tries to set property to illegal value length & width of recatngle must be >= 0 public void setWidth(double newWidth) { // object to negative widths if (newWidth < 0) { String message = "Illegal width: " + newWidth; throw new IllegalArgumentException(message); } // new width OK – make the change width = newWidth;

The throw Command Command to throw an exception is throw throw new IllegalArgumentException(message); Exception to throw usually created there Exception constructor given a message String message = "Illegal width: " + newWidth; message is printed out if program crashes

Exercise Rewrite the following constructor to throw an exception if either argument is negative public Rectangle(double reqWidth, double reqHeight) { if (reqWidth >= 0) { width = reqWidth; } else { width = 0; } if (reqHeight >= 0) { height = reqHeight; height = 0;

Catching Exceptions try-catch block … // code that may throw an exception } catch(ExceptionClass exceptionObject) { … // code to handle the exception } Try to do this, and if something goes wrong, do this to deal with it

Catching Exceptions For catching InputMismatchException inside the number-reading loop try { num = kbd.nextDouble(); // may throw an exception kbd.nextLine(); } catch(InputMismatchException ime) { System.out.println(“That’s not a number!”); break; // exit from loop Note: it’s a parameter! see CatchInputMismatch.java

When No Exceptions Occur while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); break; // exit from loop

When An Exception Occurs while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); // doesn’t even get to finish! kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); break; // exit from loop

Notes InputMismatchException part of java.util needs to be imported along with Scanner import java.util.Scanner; import java.util.InputMismatchException; Our program exits the loop because of the break command normally would continue on inside the loop (or whatever comes after the catch block)

When an Exception Occurs… Code in try block gets skipped right out from where the exception occurred // read an integer and save it in num num = kbd.nextInt(); // skip the rest of the input line kbd.nextLine(); if next thing isn’t an int, NONE of that happens doesn’t read an integer (no integer there to be read!) doesn’t save anything in num (num unchanged!) doesn’t skip rest of line

Dealing with Exceptions After catching the exception, the body of the catch block is executed does whatever it says to do print a message; break out of a loop Question to ask yourself: What do I want my program to do when it catches this exception?

What Do I Want to Do? Reading int values; non-int value entered try { num = kbd.nextInt(); } catch (InputMismatchException ime) { end the loop? break; skip invalid data? kbd.next(); } but if you skip, what else might go wrong?

Exercise What happens with the following code when the user enters a non-number? while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); kbd.nextLine(); What goes wrong? How might we fix it?

Bigger Try Blocks Enter a word instead of the first number program crashes! Catch blocks only catch exceptions from the corresponding try blocks exceptions from outside don’t get caught Try block can be as big as you want so long as it stays inside the method

A Loop inside a try Block Exception  stop reading numbers even if it’s the first number! int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } catch (InputMismatchException ime) {} System.out.println(“The sum is ” + sum); What does the catch block do here?

Exercise Revise the code so that the sum is only printed if the loop ends “normally” that is, by the user entering a negative number int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } } catch (InputMismatchException ime) { System.out.println(“The sum is ” + sum); NOTE: You don’t need to add any code. Just move a piece of it!

Our Own Exception Classes Usually use a built-in exception class e.g. IllegalArgumentException Can create our own exception classes if none of the available ones is exactly right or want to distinguish different problems We will extend RuntimeException extending Exception leads to complications or some other suitable RuntimeException

Our Own Exception Class NotEnufMilkException represents not having enuf milk public class NotEnufMilkException extends RuntimeException { public NotEnufMilkException() { super(“Not enuf milk!”); } public NotEnufMilkException(String message) { super(message); see NotEnufMilkException.java

Our Own Exception Classes Name ends with Exception just so we’re clear about what it is! Consists of two constructors default constructor calls super with a default message (or no message) super("Not enuf milk!"); constructor with String parameter calls super with that String super(message);

Another Exception Class NotEnufCookiesException public class NotEnufCookiesException extends RuntimeException { public NotEnufCookiesException() { super(“Not enuf cookies!”); } public NotEnufCookiesException(String message) { super(message); What exactly is the difference between this exception class definition and the previous one? see NotEnufCookiesException.java

Catching Different Exceptions Can have more than one catch block each has a different exception it catches try { … } catch(NotEnufMilkException e) {…} catch(NotEnufCookiesException e) {…} if an exception is thrown, it goes to the matching catch block if no matching block, it keeps going until it is caught, or until it gets out the top (crash!) see RoomReports.java

More Constructors Every Exception class should have constructors for () and (String) every built in Exception class does Can add more of our own assignment number is an int public IllegalAssignmentException(int asgn) { super("No such assignment: " + asgn); } need to call super(String) – no super(char)!

Questions?