CS 2511 Fall 2014.  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.

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 Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
„Exceptions”. Exceptions Handling errors with exceptions Golden rule of programming: Errors occur in software programs. What really matters is what happens.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
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)
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 Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
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.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11.
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.
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.
Handling Errors with Exception (in Java) Project 10 CSC 420.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
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.
Java I/O Input: information brought to program from an external source
CS203 Java Object Oriented Programming Errors and Exception Handling.
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
Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
Exceptions In this lecture:
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Advanced Programming Behnam Hatami Fall 2017.
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.
04/14/14 Exceptions.
ATS Application Programming: Java Programming
OBJECT ORIENTED PROGRAMMING
Web Design & Development Lecture 7
Intro to Exceptions (c) Eraj Basnayake
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
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.
Java Basics Exception Handling.
Presentation transcript:

CS 2511 Fall 2014

 Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out of bounds array access; Divide by zero, etc.  When an exception occurs, the executing method creates an Exception object and hands it to the runtime system--"throwing an exception"  The runtime system searches the runtime call stack for a method with an appropriate handler, which "catches the exception"

 Java is fussy about (some) exceptions, requiring that the programmer either:  deal with the exceptions when they occur, using try and catch, or  explicitly hand off the exception to the method that calls the method in which the exception occurs, effectively "passing the buck" to the calling method.  The exceptions Java is fussy about are called "checked" exceptions, because the compiler will check that one of the above options is satisfied

1. Separating Error Handling Code from "Regular" Code 2. Propagating Errors Up the Call Stack 3. Grouping Error Types and Error Differentiation

readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } Example: Here is pseudocode for reading a file into memory:

 What happens if the file can't be opened?  What happens if the length of the file can't be determined?  What happens if enough memory can't be allocated?  What happens if the read fails?  What happens if the file can't be closed?

errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }

readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } Note that the error handling code and "regular" code are separate

method1 { call method2; } method2 { call method3; } method3 { call readFile; } method1 method2 method3 readFile Call Stack Suppose also that method1 is the only method interested in the errors that occur within readFile. How does the error code get propogated up the stack? call

method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } method1 method2 method3 readFile Call Stack call return

method1 { try { call method2; } catch (exception) { doErrorProcessing; } method2 throws exception { call method3; } method3 throws exception { call readFile; } method1 method2 method3 readFile Call Stack call throw

Java exceptions are first class Java objects, and so they are grouped into a class hierarchy. For example: Exception RunTimeException ArithmeticException NullPointerException IOException FileNotFoundException MalformedURLException

import java.io.*; public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w; System.out.print("Source file name: "); String inFileName = br.readLine(); r = new FileReader(inFileName); System.out.print("Destination file name: "); String outFileName = br.readLine(); w = new FileWriter(outFileName); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

4% java FileCopy Source file name: foo Exception in thread "main" java.io.FileNotFoundException: foo (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:39) at FileCopy.main(FileCopy.java:12) 5% In the example, the main method chooses to "pass the buck," but there is nowhere to pass it to. Thus, the program will crash:

public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w; System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); System.out.print("Source file name: "); inFileName = br.readLine(); r = new FileReader(inFileName); }... }

This approach will catch the first instance of a FileNotFoundException, but only that instance: 5% java FileCopy Source file name: foo foo (No such file or directory) Source file name: bar Exception in thread "main" java.io.FileNotFoundException: bar (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:39) at FileCopy.main(FileCopy.java:19) 6% Note that you can use the getMessage() method (inherited by the Exception class) in your handler.

public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = null; FileWriter w = null; boolean fileFound; do { fileFound = true; System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { fileFound = false; System.out.println(ex.getMessage()); } } while ( !fileFound );... }

226% java FileCopy Source file name: foo foo (No such file or directory) Source file name: bar bar (No such file or directory) Source file name: foo foo (No such file or directory) Source file name: bar bar (No such file or directory) Source file name: X.java Destination file name: Y.java 227%

public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = getFileReader(br); FileWriter w = getFileWriter(br); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

private static FileReader getFileReader(BufferedReader br) { System.out.print("Source file name: "); try { String inFileName = br.readLine(); return new FileReader(inFileName); } catch(IOException ex) { System.out.println(ex.getMessage()); return getFileReader(br); } Note: No looping code needed. Since the exception is caught, no throws clause is necessary.

private static FileWriter getFileWriter(BufferedReader br) { System.out.print("Destination file name: "); try { String outFileName = br.readLine(); return new FileWriter(outFileName); } catch(IOException ex) { System.out.println(ex.getMessage()); return getFileWriter(br); } Now the only calls in main that can throw an exception are read, write, and flush

public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = getFileReader(br); FileWriter w = getFileWriter(br); int c; try { while ((c = r.read()) != -1) w.write(c); w.flush(); } catch(IOException ex) { System.out.println(ex.getMessage()); } Now the program will not crash if/when an I/O error occurs.

 A program that catches all I/O exceptions may still experience a different type of exception (say, a runtime exception)  I/O exceptions are "checked" by the compiler  That is, you are required to either catch them or mention them in a throws clause  Unlike I/O exceptions, runtime exceptions are "unchecked"  That is, you can choose to ignore them at your peril

 IOException and any of its subclasses  InterruptedException (thrown when a thread is interrupted)  Any exception you invent by subclassing Exception

 Subclasses of RuntimeException :  ArithmeticException  IllegalArgumentException  NumberFormatException  IndexOutOfBoundsException  ArrayIndexOutOfBoundsException  StringIndexOutOfBoundsException  NullPointerException  Those that you invent by subclassing RuntimeException

 Exceptions are processing conditions that a program ought to be able to recover from if it is robust enough  Errors are conditions that are ordinarily not recoverable:  Death of a thread  Linking error  Virtual machine error

 Exception s and Error s are both subclasses of the Throwable class: Object Throwable ErrorException LinkageErrorThreadDeathVirtualMachineError