Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
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.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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 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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Object Oriented Programming
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
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 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.
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 Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Java Exceptions a quick review….
Introduction Exception handling Exception Handles errors
Introduction to OO Program Design
Creating and Modifying Text part 2
Handling Exceptions.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Java Exception Very slightly modified from K.P. Chow
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.
Tutorial Exceptions Handling.
Java Basics Exception Handling.
Presentation transcript:

Exceptions 1

Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException: student.txt (The system cannot find the file specified.) Exception in thread “main” java.lang.NullPointerException: at FileProcessor.main(FileProcessor.java:9) Question: do all run-time errors cause Exceptions?

Causes of Exceptions Most exceptions happen because of “corner cases”:  your program does something at the boundaries of what Java knows how to handle. For example:  Java knows how to open files for reading, mostly.  But if you tell it to open a file that doesn’t exist, it doesn’t know how it should behave.  It throws an exception, and gives the programmer an opportunity to define how the program should react.

The Exception Class As with anything in Java, Exception is a class The methods in the Exception class can be useful for debugging, as we will see. MethodWhat it does void printStackTrace()Prints the sequence of method calls leading up to the statement that caused the Exception. String getLocalizedMessage()Returns a “detail” message. String toString()Returns the Exception class name and detail message.

The Exception class hierarchy (partial) Throwable ErrorException IOExceptionClassNotFound Exception Runtime Exception EOFExceptionFileNotFound Exception UnknownHost Exception Arithmetic Exception ClassCast Exception IndexOut OfBounds Exception NullPointer Exception

Pitch and catch When a Java statement causes an Exception (called throwing the Exception), by default Java abruptly ends the program. To stop this default behavior, you can write code that catches the thrown Exception.

Catch: An example import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) { try { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); while(input.hasNextLine()) { System.out.println("> " + input.nextLine()); } catch(FileNotFoundException exception) { System.out.println("Could not find the file 'student.txt'."); }

try/catch syntax try { ; } catch( e1) { } … catch( eN) { } try block indicates that the enclosed statements have exception handlers associated with them. catch block is an exception handler for one type of exception. The type of exception that the catch block handles is indicated with a parameter. You can have as many catch blocks for one try block as you like. They must each handle a different type of exception.

Control Flow with try/catch try { ; } catch( e1) { } … catch( eN) { }  If no exception occurs during the try block:  jump to statements after all the catch blocks.  If an exception occurs in the try block:  jump to the first handler for that type of exception.  After the catch finishes, jump to the statement after all the catch blocks.

Catch: An example import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) { try { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); while(input.hasNextLine()) { System.out.println("> " + input.nextLine()); } catch(FileNotFoundException exception) { System.out.println("Could not find the file 'student.txt'."); }

Stack Traces How do you know what went wrong? All exceptions have methods that return information about the cause of the Exception: MethodDescription getLocalizedMessage()Returns a String containing a description of the error getStackTrace()Returns an array of StackTraceElement objects, each of which contains info about where the error occurred printStackTrace()Displays the Stack Trace on the console.

Displaying the stack trace info import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) { try { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); while(input.hasNextLine()) { System.out.println("> " + input.nextLine()); } catch(FileNotFoundException exception) { System.out.println("Could not find the file 'student.txt'."); System.out.println(exception.getLocalizedMessage()); exception.printStackTrace(); }

Multiple catch blocks import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) { try { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); PrintWriter pw = new PrintWriter(new File(“quoted.txt”)); while(input.hasNextLine()) { pw.println("> " + input.nextLine()); } catch(FileNotFoundException exception) { System.out.println("Could not find the file 'student.txt'."); } catch(IOException exception) { System.out.println(“Could not write to file ‘quoted.txt’.”); }

Multiple catch blocks import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) { try { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); PrintWriter pw = new PrintWriter(new File(“quoted.txt”)); while(input.hasNextLine()) { pw.println("> " + input.nextLine()); } catch(FileNotFoundException exception) { System.out.println("Could not find the input file."); System.out.println(exception.getLocalizedMessage()); exception.printStackTrace(); } catch(IOException exception) { System.out.println(“Could not write to file ‘quoted.txt’.”); }

Catch: An exercise Write a FileCopier.java class that copies a text file and catches any exceptions.

Finally, to close a file Remember: You need to close every file you open! For example, FileInputStream fis = new FileInputStream(new File(“song.mp3”)); int nextByte = fis.read(); … fis.close();

An example of improper closing import java.io.*; public class FileProcessor { public static void main(String [] args) { try { FileInputStream fis = new FileInputStream(new File(“song.mp3”)); int nextByte = fis.read(); while(nextByte>=0) { System.out.println(nextByte); nextByte = fis.read(); } fis.close(); } catch(FileNotFoundException exception) { System.out.println("Could not find the file 'student.txt'."); } catch(IOException ioe) { System.out.println(“Error reading from file!”); }

The finally statement import java.io.*; public class FileProcessor { public static void main(String [] args) { try { FileInputStream fis = new FileInputStream(new File(“song.mp3”)); int nextByte = fis.read(); while(nextByte>=0) { System.out.println(nextByte); nextByte = fis.read(); } catch(FileNotFoundException exception) { System.out.println("Could not find the file ‘song.mp3'."); } catch(IOException ioe) { System.out.println(“Error reading from file!”); } finally { fis.close(); } But the close() statement itself might cause an exception!

The finally statement, second version import java.io.*; public class FileProcessor { public static void main(String [] args) { try { FileInputStream fis = new FileInputStream(new File(“song.mp3”)); int nextByte = fis.read(); while(nextByte>=0) { System.out.println(nextByte); nextByte = fis.read(); } catch(FileNotFoundException exception) { System.out.println("Could not find the file ‘song.mp3'."); } catch(IOException ioe) { System.out.println(“Error reading from file!”); } finally { try { fis.close(); } catch(IOException ioe) { System.out.println(“Error closing file”); } But fis is not in scope!

The finally statement, third version import java.io.*; public class FileProcessor { public static void main(String [] args) { FileInputStream fis = null; try { fis = new FileInputStream(new File(“song.mp3”)); int nextByte = fis.read(); while(nextByte>=0) { System.out.println(nextByte); nextByte = fis.read(); } catch(FileNotFoundException exception) { System.out.println("Could not find the file ‘song.mp3'."); } catch(IOException ioe) { System.out.println(“Error reading from file!”); } finally { try { fis.close(); } catch(IOException ioe) { System.out.println(“Error closing file”); }

The finally statement, final (shorter) version import java.io.*; public class FileProcessor { public static void main(String [] args) { FileInputStream fis = null; try { fis = new FileInputStream(new File(“song.mp3”)); try { int nextByte = fis.read(); while(nextByte>=0) { System.out.println(nextByte); nextByte = fis.read(); } finally { fis.close(); } catch(FileNotFoundException exception) { System.out.println("Could not find the file ‘song.mp3'."); } catch(IOException ioe) { System.out.println(“Error reading from file!”); }

finally vs. return What does the following code print out? public class Test { public static void main(String args[]) { System.out.println(Test.test()); } public static int test() { try { return 0; } finally { System.out.println("finally trumps return?"); } } } Output: finally trumps return? 0

Finally exercise Add finally and close statements to the FileCopier.java

Checked and Unchecked Exceptions Exceptions happen while the program is running For most kinds of Exceptions, the compiler is happy to let the programmer make mistakes that could lead to an exception at run- time. Unchecked (by the compiler) Exceptions  They are caused by programmer error.  The compiler lets the programmer screw up.  e.g., NullPointerException, IndexOutOfBoundsException

Checked and Unchecked Exceptions Exceptions happen while the program is running For most kinds of Exceptions, the compiler is happy to let the programmer make mistakes that could lead to an exception at run- time. But, for certain kinds of exceptions, the compiler will check to see if your code might cause an exception at run-time. Checked (by the compiler) Exceptions:  They are caused by things outside of the programmer’s control (eg, a file doesn’t exist).  The compiler requires that the programmer declare what to do if the Exception occurs.

Checked and Unchecked Exceptions Throwable ErrorException IOExceptionClassNotFound Exception Runtime Exception EOFExceptionFileNotFound Exception UnknownHost Exception Arithmetic Exception ClassCast Exception IndexOut OfBounds Exception NullPointer Exception

Options for Checked Exceptions If the compiler detects that a statement might cause a Checked Exception, it requires the programmer to do either of the following: 1. Catch the Exception 2. Declare that crashing is acceptable  Use the throws clause in the method signature Otherwise, the program will not compile.

Throws: An example import java.util.*;// For Scanner class import java.io.*; public class FileProcessor { public static void main(String [] args) throws FileNotFoundException { File inputFile = new File("student.txt"); Scanner input = new Scanner(inputFile); while(input.hasNextLine()) { System.out.println("> " + input.nextLine()); }

Catch or throw? When should you catch an exception, and when should you declare that it can be thrown? Usually, if your catch block is not going to do anything besides print an error message and quit the program, it’s better to just throw the exception You should only catch an exception if you’re really going to handle the error so that it won’t affect the rest of the program.

Causing a ruckus Guess what … you can create your very own Exceptions, any time you want! The throw keyword: (note: NOT the same as the throws keyword!)  Use it to make your code throw an exception throw new Exception();  Mainly useful for passing messages between methods that aren’t easily done with returns