Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling Part 1: Handing Java Exceptions CSIS 3701: Advanced Object Oriented Programming.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
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.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and 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.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
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.
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Chapter 9: Exceptions For error/problem situations Exception classes –ArithmeticException, IOException, etc. –checked exceptions try blocks –catch statements.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
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. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Exception Handling.
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Creating and Modifying Text part 2
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
EE422C Software Implementation II
Chapter 12 Exception Handling
Exception Handling.
Chapter 11 Input/Output Exception Handling
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions.
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.
Exceptions.
Exceptions and Exception Handling
Presentation transcript:

Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy the situation). The concept: perhaps the caller of the method would know what to do, and can ‘handle’ the problem. If the calling method does NOT handle the situation, the exception is thrown to it’s caller … and so forth. Eventually the exception reachs the main method. If main doesn’t ‘handle’ the exceptional situation, the program terminates with a stack trace. IDEALLY, THIS SHOULDN’T HAPPEN !!!! THE PROGRAM SHOULD HANDLE (CATCH) EXCEPTION before THE PROGRAM TERMINATES !!

General Try Block Syntax General Try Block Syntax try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }

Perhaps the block of code can generate a number of exceptions.. prepare to catch each type…. try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }...

Execution behavior ……..  Statements in try block are executed  If no exceptions occur, catch clauses are skipped  If exception of matching type occurs, execution jumps to catch clause and execution continues  If exception of another type occurs, it is thrown to the calling method

Catching Exceptions try { BufferedReader in = new BufferedReader( new FileReader(“filename.txt”)); String inputLine = in.readLine(); int age = Integer.parseInt(inputLine); age++; } catch (IOException exception) { age = 0; System.out.println(“file not found/default used“+ +exception); } catch (NumberFormatException exception) { age = 0; }

public void computeAvg ( int max) { BufferedReader console = new BufferedReader(new BufferedReader console = new BufferedReader(new InputStreamReader(System.in); InputStreamReader(System.in); try { int [] list = new int[max]; try { int [] list = new int[max]; } catch ( NegativeArraySizeException exception) { catch ( NegativeArraySizeException exception) { System.out.println(“how many values??”); System.out.println(“how many values??”); max = Integer.parseInt(console.readLine()); max = Integer.parseInt(console.readLine()); int [] list = new int[max]; int [] list = new int[max]; } try{ try{ System.out.println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) System.out.println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) list[index] = Integer.parseInt(console.readLine()); } list[index] = Integer.parseInt(console.readLine()); } catch (NumberFormatException exception) { throw new IllegalStateException(“average can’t be computed”); catch (NumberFormatException exception) { throw new IllegalStateException(“average can’t be computed”); } catch (IndexOutofBounds e) { catch (IndexOutofBounds e) { throw new IllegalStateException(“array full:average can’t be computed” + e); throw new IllegalStateException(“array full:average can’t be computed” + e);}

The finally Clause  Sometimes there is code which needs to be executed EVEN IF an exception occurred  Example: BufferedReader in; in = new BufferedReader(new FileReader(filename)); purse.read(in); in.close();  Must execute in.close() even if exception happens

The finally Clause Syntax try { statement statement... } finally { try { statement statement... } finally { statement statement... } statement statement... }

The finally Clause  Executed when try block comes to normal end  Executed if a statement in try block throws an exception, before exception is thrown out of try block  Can also be combined with catch clauses

BufferedReader in = null; try { in = new BufferedReader( new FileReader(filename)); purse.read(in); } finally { if (in !=null) in.close(); } try { in = new BufferedReader( new FileReader(filename)); purse.read(in); } finally { if (in !=null) in.close(); }

A Complete Example  Program  Program oreads lines coin quantities and coin names from file o adds coins to purse oprints total  What can go wrong? oFile might not exist oFile might have data in wrong format  Who can detect the faults? omain method of PurseTest interacts with user omain method can report errors oOther methods pass exceptions to caller

The read method of the Coin class //reads a value and name from file, stores as instance data public boolean read(BufferedReader in) throws IOException { String input =in.readLine(); if (input == null) // normal end of file return false; value = Double.parseDouble(input); // may throw unchecked NumberFormatException name = in.readLine(); if (name == null) // unexpected end of file throw new EOFException("Coin name expected"); return true; }

The read method of the Purse class Unconcerned with exceptions Unconcerned with exceptions Just passes them to caller Just passes them to caller public void read(BufferedReader in) throws IOException { boolean done = false; while (!done) { Coin c = new Coin(); if (c.read(in)) add(c); else done =true; } add(c); else done =true; }}

The readFile method of the Purse class finally clause closes files if exception happens public void readFile(String filename) throwsIOException { BufferedReader in = null; try { //two possible sources of IOExceptions in = new BufferedReader( new FileReader(filename)); read(in); } finally { if (in != null) in.close(); } }

User interaction in main If an exception occurs, user can specify another file name boolean done = false; String filename = JOptionPane.showInputDialog("Enter file name"); while (!done) { try { Purse myPurse = new Purse(); myPurse.readFile(filename); System.out.println("total=" + myPurse.getTotal()); done =true; }

catch (IOException exception) { System.out.println("Input/output error " + exception); } catch (NumberFormatException exception) { exception.printStackTrace(); // error in file format } if (!done) //an exception occurred { Filename = JOptionPane.showInputDialog("Try another file:"); if (filename == null) done =true; } }

Scenario 1. PurseTest.main calls Purse.readFile 2. Purse.readFile calls Purse.read 3. Purse.read calls Coin.read 4. Coin.read throws an EOFException 5. Coin.read has no handler for the exception and terminates immediately. 5. Coin.read has no handler for the exception and terminates immediately. 6. Purse.read has no handler for the exception and terminates immediately 7. Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file. 7. Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file. 8. PurseTest.main has a handler for an IOException, a superclass of EOFException. That handler prints a message to the user. Afterwards, the user is given another chance to enter a file name. Note that the statement printing the purse total has been skipped.