James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.

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

Yoshi
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
COMP 121 Week 5: Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
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.
James Tam Simple File Input And Output You will learn how to write to and read from text and serialized files in Java.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java Writing and reading objects to and from.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
Simple File Input And Output
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Creating and Modifying Text part 2
הרצאה 12: קבצים וחריגות (Exceptions)
استفاده از فایلها در جاوا
Exception Handling and Reading / Writing Files
Exception Handling.
Web Design & Development Lecture 7
Simple File Input And Output
Simple File Input And Output
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Java Basics Exception Handling.
Exceptions and Exception Handling
Java Exception Handling
Presentation transcript:

James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism

James Tam Exception handling in Java Approaches For Dealing With Error Conditions Use conditional statements and return values Use Java’s exception handling mechanism

James Tam Exception handling in Java Approaches For Dealing With Error Conditions Use conditional statements and return values Use Java’s exception handling mechanism

James Tam Exception handling in Java Class Inventory: An Earlier Example class Inventory { public boolean addToInventory (int amount) { int temp = stockLevel + amount; if (temp > MAX) { System.out.print("Adding " + amount + " item will cause stock "); System.out.println("to become greater than " + MAX + " units"); return false; } else { stockLevel = stockLevel + amount; return true; } :

James Tam Exception handling in Java Some Hypothetical Method Calls: Condition/Return store.addToInventory (int amt) If (temp > MAX) return false; object2.method2 () If (store.addToInventory(amt) == false) return false; object1.method1 () If (object2.method2() == false) return false;

James Tam Exception handling in Java Some Hypothetical Method Calls: Condition/Return store.addToInventory (int amt) If (temp > MAX) return false; object2.method2 () If (store.addToInventory(amt) == false) return false; object1.method1 () If (object2.method2() == false) return false; Problem 1: The calling method may forget to check the return value

James Tam Exception handling in Java Some Hypothetical Method Calls: Condition/Return store.addToInventory (int amt) If (temp > MAX) return false; object2.method2 () If (store.addToInventory(amt) == false) return false; object1.method1 () If (object2.method2() == false) return false; Problem 2: A long series of method calls requires many checks/returns

James Tam Exception handling in Java Some Hypothetical Method Calls: Condition/Return store.addToInventory (int amt) If (temp > MAX) return false; object2.method2 () If (store.addToInventory(amt) == false) return false; object1.method1 () If (object2.method2() == false) return false; Problem 3: The calling method may not know how to handle the error ???

James Tam Exception handling in Java Approaches For Dealing With Error Conditions Use conditional statements and return values Use Java’s exception handling mechanism

James Tam Exception handling in Java Handling Exceptions Format: try { // Code that may cause an exception to occur } catch (ExceptionType identifier) { // Code to handle the exception }

James Tam Exception handling in Java Handling Exceptions: An Example Revisited The complete program can be found in the directory: /home/profs/tamj/233/examples/exceptions/handlingExceptions/firstExample class SimpleIO { public static void main (String [] argv) { : try { fw = new FileWriter (filename); : } catch (IOException e) { : }

James Tam Exception handling in Java Handling Exceptions: An Example Revisited FileWriter (String filename) { : } SimpleIO.main () try { fw = new FileWriter (filename); } catch (IOException e) { : }

James Tam Exception handling in Java Handling Exceptions: An Example Revisited FileWriter (String filename) { } SimpleIO.main () try { fw = new FileWriter (filename); } catch (IOException e) { : } Oops! Can’t write to file

James Tam Exception handling in Java Handling Exceptions: An Example Revisited FileWriter (String filename) { } SimpleIO.main () try { fw = new FileWriter (filename); } catch (IOException e) { : } IOException thrown IOException e= new IOException ()

James Tam Exception handling in Java Handling Exceptions: An Example Revisited FileWriter (String filename) { } SimpleIO.main () try { fw = new FileWriter (filename); } catch (IOException e) { : } IOException thrown IOException e= new IOException ()

James Tam Exception handling in Java Handling Exceptions: An Example Revisited FileWriter (String filename) { } SimpleIO.main () try { fw = new FileWriter (filename); } catch (IOException e) { } IOException must be dealt with here

James Tam Exception handling in Java try { fw = new FileWriter (filename); pw = new PrintWriter (fw); pw.println(iw1.getNum()); pw.close(); fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); } Handling Exceptions: An Example Revisited

James Tam Exception handling in Java try { fw = new FileWriter (filename); pw = new PrintWriter (fw); pw.println(iw1.getNum()); pw.close(); fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); } Handling Exceptions: An Example Revisited Exception 1

James Tam Exception handling in Java Where The Exceptions Occur In Class FileWriter For online documentation for this class go to: Class FileWriter { public FileWriter (String fileName) throws IOException; public FileWriter (String fileName, boolean append) throws IOException; : }

James Tam Exception handling in Java try { fw = new FileWriter (filename); pw = new PrintWriter (fw); pw.println(iw1.getNum()); pw.close(); fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); } Handling Exceptions: An Example Revisited Exception 2

James Tam Exception handling in Java Where The Exceptions Occur In Class FileReader For online documentation for this class go to: Class FileReader { public FileReader (String fileName) throws FileNotFoundException; public FileReader (File file) throws FileNotFoundException; : }

James Tam Exception handling in Java try { fw = new FileWriter (filename); pw = new PrintWriter (fw); pw.println(iw1.getNum()); pw.close(); fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); } Handling Exceptions: An Example Revisited Exception 3

James Tam Exception handling in Java Where The Exceptions Occur In Class BufferedReader For online documentation for this class go to: Class BufferedReader { public BufferedReader (Reader in); public BufferedReader (Reader in, int sz); public String readLine () throws IOException; : }

James Tam Exception handling in Java Handling Exceptions: An Example Revisited catch (IOException e) { System.out.println("File IO error: Exception thrown"); System.out.println(e); System.out.println(); e.printStackTrace(); }

James Tam Exception handling in Java Handling Exceptions: An Example Revisited catch (IOException e) { System.out.println("File IO error: Exception thrown"); System.out.println(e); System.out.println(); e.printStackTrace(); } java.io.FileNotFoundException: data (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream. (FileInputStream.java:103) at java.io.FileInputStream. (FileInputStream.java:66) at java.io.FileReader. (FileReader.java:41) at SimpleIO.main(SimpleIO.java:35)

James Tam Exception handling in Java Common Exceptions NullPointerException ArrayIndexOutOfBoundsException ArithmeticException

James Tam Exception handling in Java Common Exceptions: An Example int [] arr = null; arr[0] = 1; arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; arr[i-1] = arr[i-1] / 0; NullPointerException

James Tam Exception handling in Java Common Exceptions: An Example int [] arr = null; arr[0] = 1; arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; arr[i-1] = arr[i-1] / 0; ArrayIndexOutOfBoundsException (when i = 4)

James Tam Exception handling in Java Common Exceptions: An Example int [] arr = null; arr[0] = 1; arr = new int [4]; int i; for (i = 0; i <= 4; i++) arr[i] = i; arr[i-1] = arr[i-1] / 0; ArithmeticException (Division by zero)

James Tam Exception handling in Java Categories Of Exceptions Unchecked exceptions Checked exception

James Tam Exception handling in Java Unchecked Exceptions The compiler doesn’t require you to handle them if they are thrown. They can occur at any time in the program (not just for a specific method) Typically they are fatal runtime errors that are beyond your control Use conditional statements rather than the exception handling model. Examples: NullPointerException,IndexOutOfBoundsException, ArithmeticException…

James Tam Exception handling in Java Checked Exceptions Must be handled if they are ever thrown Use a try-catch block Deal with problems that occur in a specific place When a particular method invoked Example: IOException

James Tam Exception handling in Java Avoid Squelching Your Exceptions try { fw = new FileWriter (filename); } catch (IOException e) { // Do nothing here. Just set up the try-catch block to bypass those pesky // syntax errors. }

James Tam Exception handling in Java Avoid Squelching Your Exceptions try { fw = new FileWriter (filename); } catch (IOException e) { // Do nothing here. Just set up the try-catch block to bypass those pesky // syntax errors. } NO!

James Tam Exception handling in Java The Finally Clause Part of Java’s exception handling model (try-catch-finally) Used to enclose statements that must always be executed.

James Tam Exception handling in Java The Finally Clause try { } catch { } finally { }

James Tam Exception handling in Java The Finally Clause: Exception Thrown try { } catch { } finally { } 2) Exception is thrown and caught 3) Control transfers to the finally clause 1) Statements in the try block are attempted

James Tam Exception handling in Java The Finally Clause: No Exception Occurs try { } catch { } finally { } 1) Statements in the try block are completed 2) Control transfers to the finally clause

James Tam Exception handling in Java Try-Catch-Finally: An Example The complete program can be found in the directory: /home/profs/tamj/233/examples/exceptions/handlingExceptions/secondExample

James Tam Exception handling in Java Try-Catch-Finally: An Example (2) try { BufferedReader br = new BufferedReader(new FileReader("phil")); String s = br.readLine(); while (s != null) s = br.readLine(); return; } catch (IOException e) { e.printStackTrace(); return; } finally { System.out.println(" >>"); return; }

James Tam Exception handling in Java When The Caller Can’t Handle The Exceptions main () method 1 ()method 2 () Exception thrown! ???

James Tam Exception handling in Java When The Caller Can’t Handle The Exceptions: An Example The complete program can be found in the directory: /home/profs/tamj/233/examples/exceptions/handlingExceptions/thirdExample import java.io.*; class IntermediateIO { public static void main (String [] argv) { method1 (); }

James Tam Exception handling in Java When The Caller Can’t Handle The Exceptions: An Example (2) public static void method1 () { try { method2 (); return; } catch (IOException e) { System.out.println("IOException thrown while reading input file"); e.printStackTrace(); return; }

James Tam Exception handling in Java When The Caller Can’t Handle The Exceptions: An Example (3) public static void method2 () throws IOException { BufferedReader br = null; String s; br = new BufferedReader(new FileReader("phil")); s = br.readLine(); while (s != null) { System.out.println(s); s = br.readLine(); } return; }

James Tam Exception handling in Java Summary Handling exceptions with the try-catch block Checked vs. unchecked exceptions Using the finally clause to guarantee the execution of clean- up statements regardless of whether an exception occurs or not.