Java Programming Transparency No. 1-1 Java Exception Handling Cheng-Chia Chen.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Programming Transparency No. 1-1 Lecture 3.3. Java Exception Handling Cheng-Chia Chen.
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.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
1 Advanced Flow of Control - Introduction - zTwo additional mechanisms for controlling process execution are exceptions and threads zChapter 14 focuses.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
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.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
1 Lecture 11(chap 14) Exception Handling & Thread Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
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.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
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.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Copyright © Curt Hill Error Handling in Java Throwing and catching 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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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.
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.
CSE 1201 Object Oriented Programming
Chapter 10 – Exception Handling
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
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.
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Chapter 11 Exceptions Java Software Solutions
Java Basics Exception Handling.
Chapter 15 – Exception Handling
Presentation transcript:

Java Programming Transparency No. 1-1 Java Exception Handling Cheng-Chia Chen

Basic Java Syntax Transparency No. 1-2 Contents 1.Traditional approach to program errors/exceptions 2.Java’s exception handling 3.The try statement 4.Exception propagation 5.The catch clause 6.The finally clause

Basic Java Syntax Transparency No. 1-3 Unexpected conditions which may arise during program execution  called exceptions  Examples: System file or i/o errors, disk full or unavailable, socket connection closed. Program file or i/o errors, unexpected EOF, file not found. Programmer errors, array subscript out of bounds, System errors, unable to load class file, problems with JVM.  Traditional approach to exceptions: mechanism: return value indicating occurrence of exceptions + special error_code variable storing exact type or details of errors problems: 1. Exceptions are not forced to be handled and error checking may be ignored entirely. 2. difficult to deal with when there are many types of exceptions that need to be handled.

Basic Java Syntax Transparency No. 1-4 Example: // this call may raise exceptions dbh = dbm_open(dbname, 0, GDBM_WRCREAT, … ); // check/handle all possible exceptions raised from previous call. if (dbh == NULL) { // NULL indicates exceptions logTime(); // error code stored in dbm_errno const char *ret = dbm_strerror(dbm_errno); fprintf(stderr, "ERROR Unable to open database: %s.\n", ret); fflush(stderr); return -1; }

Basic Java Syntax Transparency No. 1-5 Java’s Exceptions  An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught  A program can therefore be separated into a normal execution flow and an exception execution flow

Basic Java Syntax Transparency No Exception Handling  A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program  The manner in which an exception is processed is an important design consideration

Basic Java Syntax Transparency No Exception Handling  If an exception is ignored by the program, the program will terminate and produce an appropriate message  The message includes a call stack trace that indicates on which line the exception occurred The call stack trace also shows the sequence of method calls that lead to the occurrence of the exception. See Zero.java

Basic Java Syntax Transparency No. 1-8 Java’s call stack on executing Zero public class Zero { static int divide(int x,int y) { return x/y; // exception occurs here } public static void main(String[] args) { int x = 10; int y = 0; System.out.println ( divide(x,y)); // and here } // method main } // class Zero  java Zero  java.lang.ArithmeticException: / by zero  at Zero.divide(Zero.java:3)  at Zero.main(Zero.java:11) main(…) divide(…) runtime call stack stack frame for main(…) Exception occurs here

Basic Java Syntax Transparency No. 1-9 Catch an exception where it occurs public class Zero { static int divide(int x,int y) { try { return x/y; // exception occurs here } catch(Exception e) { return 0 ; } } public static void main(String[] args) { int x = 10; int y = 0; System.out.println ( divide(x,y)); } // method main } // class Zero  java Zero  0

Basic Java Syntax Transparency No Catch exceptions by calling methods public class Zero { static int divide(int x,int y) { try { return x/y; // Exception occurs here } catch(UnRelatedException e) { return 0 ; } // Exception not caught by this catch } public static void main(String[] args) { int x = 10; int y = 0; try{ out.println ( divide(x,y)); // Exception is propagated here }catch(Exception e) { // Exception get caught here! out.println( 1 ); } } // method main } // class Zero  java Zero  1

Basic Java Syntax Transparency No The try Statement  Used to detect exceptions that may occurs within its body (a try-block)  A try block is followed by one or more catch clauses, which contain code to process an exception  Each catch clause has an associated exception type  When an exception occurs, processing continues at the first catch clause that matches the exception type  See Product.java

Basic Java Syntax Transparency No import java.io.*; public class Product { public static void main (String[] args) { int x = UserReader.readInt(“Enter a number: "); int y = UserReader.readInt("Enter another number: "); System.out.println ("The product is: " + x*y ); } // method main } // class Adding class UserReader { public static int readInt (String prompt) { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); int number = 0; boolean valid = false;

Basic Java Syntax Transparency No while (! valid) { System.out.print (prompt); System.out.flush (); try { // statements possibly throwing exceptions put here!! number = Integer.parseInt (stdin.readLine()); valid = true; } catch (NumberFormatException exception) { System.out.println ("Invalid input. Try again."); } catch (IOException exception) { System.out.println ("Input problem. Terminating."); System.exit(0); } return number; } // method readInt } // class UserReader

Basic Java Syntax Transparency No Exception Propagation  If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level of some calling method.  Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level  A try block that contains a call to a method in which an exception is thrown can be used to catch that exception  See PropagationDemo.java

Basic Java Syntax Transparency No public class Propagation { static public void main (String[] args) { ExceptionScope demo = new ExceptionScope(); System.out.println("program beginning"); demo.level1(); System.out.println("program ending"); } // method main } // class Propagation class ExceptionScope { public void level3 (int a) { int c = 1; System.out.println("level3 beginning"); current = c / a; // divided by zero System.out.println("level3 ending"); } // method level3

Basic Java Syntax Transparency No public void level2() { System.out.println("level2 beginning"); level3 (0); System.out.println("level2 ending"); } // method level2 public void level1() { System.out.println("level1 beginning"); try { level2(); } catch (ArithmeticException p) { System.out.println (p.getMessage()); p.printStackTrace(); } System.out.println("level1 ending"); } // method level1 } // class ExceptionScope

Basic Java Syntax Transparency No main() : … demo.level1() … level1() : … try{ … level2() …} catch( ArithmeticException p) {…} …. level2() : … level3() … level3() : … c = c / 0; // divided by zero … normal flowexception flow Exception propagation

Basic Java Syntax Transparency No Types of Exceptions  An exception is either checked or unchecked  A checked exception can only be thrown within a try block or within a method that is declared (at the throws-clause of the method header) to throw that exception  The compiler will complain if a checked exception is not handled appropriately  An unchecked exception does not require explicit handling, though it could be processed that way In previous example, ArithmeticException is an unchecked exception, hence it need not be declared even it is not catched at method level3() and level2().

Basic Java Syntax Transparency No The throw Statement  A programmer can define an exception by extending the appropriate class  Exceptions are thrown using the throw statement: throw exception-object ;  See ThrowDemo.java  Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown

Basic Java Syntax Transparency No import java.io.IOException; public class ThrowDemo { public static void main (String[] args) throws MyExp { MyExp p = new MyExp ("Alert!"); throw p; // execution never gets to this point } // method main } // class ThrowDemo class MyExp extends IOException { MyExp (String message) { super (message); } // constructor Ooops } // class Ooops

Basic Java Syntax Transparency No The finally Clause  A try statement can have an optional clause designated by the reserved word finally  If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete  Also, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

Basic Java Syntax Transparency No The finally Clause  Exception Handling: try { code that may generate exceptions; } catch (Exception1 e1) { code to handle exception of type Exception1; } catch( …. ){ … } catch (ExceptionN eN) { code to handle exception of type ExceptionN; } finally { code that are guaranteed to be executed before (normally or abnormally) leaving this try-catch statement; }

Basic Java Syntax Transparency No Example finally-clause usage public boolean deposit(int account, int amt ){ int old, balance; old = balance =load(account); try { balance = balance + amt ; // suppose this operation may fail ! } catch (Exception e1) { balance = old ; // recover balance return false ; } finally { store( account, balance ); } return true; }

Basic Java Syntax Transparency No (Part of) the Exception Hierarchy Object  Throwable   Eorror : LinkageError, ThreadDeath, VirtualMachineError, AWTError  Exception: RuntimeException  ArithmeticException  IndexOutOfBoundException  NullPointerException  … IllegalAccessException NoSuchMethodException ClassNotFoundException IOException …  Note: Checked exception must be either catched or declared at the throws- clause of the method header.  All Throwable but Error and RuntimeException are checked Exceptions.

Basic Java Syntax Transparency No What can we get from an Exception java.lang.Throwable:  Constructor Summary Throwable() : Constructs a new Throwable with null as its error message string. Throwable([ [String msg] [, Throwable cause ]]) : Constructs a new Throwable with the specified error message and/or cause.  Method Summary Throwable fillInStackTrace() : Fills in the execution stack trace. String getLocalizedMessage() : Creates a localized description of this Throwable. String getMessage() : Returns the error message string of this throwable object. Throwable getCause(); void printStackTrace(), printStackTrace(PrintStream s), printStackTrace(PrinterWriter s) : Prints this Throwable and its backtrace to the standard error stream or s. StackTraceElement[] getStackTrace() void setStackTraceElement(StackTrace[]) String toString() : Returns a short description of this throwable object. java.lang.Exception: Constructors: Exception(), Exception(String). All methods are inherited from Throwable.

Basic Java Syntax Transparency No StackTraceElement  An element in a stack trace, as returned by Throwable.getStackTrace().  Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created.  Methods String getClassName() String getMethodName() boolean isNativeMethod() String getFileName() int getLineNumber()