Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
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.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exception Handling and Format output
Index Exception handling Exception In Java Exception Types
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:
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Exception Handling
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.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
Dr. Abraham. Exception Any problem that VB or OS could not handle Robust program A program that performs well not only under ordinary conditions but also.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Java Programming: Guided Learning with Early Objects
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching 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.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Exception Handling in C++
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Why exception handling in C++?
ATS Application Programming: Java Programming
Exception Handling in Java
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Java Basics Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

Exception Handling Yaodong Bi

Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an exception Throws clause Exceptions in constructors and finalizers Exception and inheritance The finally block PrintStackTrace() and getMessage()

Java Exception Handling To process only exceptional situations where a method is unable to complete the task for reasons it cannot control To process exceptions from program components that are not geared to handling those exceptions directly To process exceptions from components such as libraries and classes that are likely to be widely used and where those components cannot handle their own exceptions

Java Exception Handling When an exception does not occur, little or no overhead is imposed by the presence of exception handling code. When exceptions occur, they do incur execution-time overhead Use Java’s standardized exception handling to improve program clarity and fault tolerance

Exception Handling Basics When a block of code (ex., a method) detects an error it cannot handle, it throws an exception The programmer encloses in a try block the code that may throw an exception. The try block is immediately followed by zero or more catch blocks to catch the exception(s) Each catch block specifies the type of exception it can catch and contains an exception handler An optional finally block (mandatory when no catch clause provided) will be executed regardless of whether or not there is an exception.

Exception Handling Basic A method can use a throws clause to specify what exceptions it may throw Java employs the termination model of exception handling. – Once an exception is thrown, the block in which the exception is thrown terminates and control cannot return to the throw point

Ex. 1: Divide By Zero public class ExceptionHandling { public static int quotient(int numerator, int denominator) throws DivideByZeroException { if (denominator == 0) throw new DivideByZeroException(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (DivideByZeroException e) { System.err.println(e.toString()); }

Ex. 1: Divide By Zero finally {System.out.println("Finally Block"); } // the following is saved in a separate file public class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super("Divide by Zero"); } public DivideByZeroException(String s) { super(s); }

Try blocks try { // code that may throw exceptions } catch (ExceptionType ref) { // exception handler } A try block can be followed by zero or more catch blocks If the try block executes with no exception thrown, all the exception handlers are skipped and control resumes with the first statement after the last exception handler If a finally block follows the last catch block, it will be executed regardless of whether or not an exception is thrown

Throwing Exceptions The throw statement makes an exception to occur – throwing an exception – throw new DivideByZeroException(); A throw statement must throw an object of any class derived from class Throwable When an exception is thrown, control exits the current try block and proceeds to an appropriate catch handler When toString() is invoked on any Throwable object, it returns the String that was supplied to the constructor public class DivideByZeroException extends ArithmeticException {public DivideByZeroException() {super("Divide by Zero"); // return by toString() }

Catching Exceptions Each catch block starts with the keyword catch followed by parentheses containing a class name (type of exception) The Exception object caught can be referred through the parameter catch (ExceptionType ref) { // using ref to refer to the exception object } It is possible that several handlers provide an acceptable match to the type of the exception, the first exception handler that matches the exception type is executed.

Catching Exceptions Each catch block defines a distinct scope An exception handler cannot access objects defined in other handlers Objects defined in a try block cannot be accessed in its exception handlers try { int tryX = 100; … } catch (ExceptionType1 ref) {int catch1Y = 200; // tryX is NOT accessible here } catch (ExceptionType2 ref) { // both tryX and catch1Y are NOT accessible here }

Catching Exceptions Exceptions thrown from a handler cannot be caught by the catch blocks of the current try-catch structure 1 try { 2try { throw new ExcType1(); } 3catch (ExcType1 ref) 4{ 5throw new ExcType2(); 6} 7catch (ExcType2 ref) 8{ 9 // this will NOT catch the ExcType2 thrown from line 5 10} 11 catch (ExcType2 ref) 12 { 13 // catch the ExcType2 exception thrown from line 5 14 }

Re-throwing Exceptions When a exception handler cannot or does not want to handle the caught exception completely, it can re-throw the exception using the throw statement. Such a re-thrown exception is handled by the enclosing try-catch block 1 try { 2try { throw new ExcType1(); } 3catch (ExcType1 ref) 4{ 5throw ref; 6} 7 catch (ExcType1 ref) 8 { 9 // catch the ExcType1 exception thrown from line 5 10 }

Throws Clause A throws clause lists the exceptions that can be thrown by a method void foo() throws ExceptionA, ExceptionB ExceptionA {// may throw the above three exceptions } All exceptions must be handled exception Error and RuntimeException If a method does not handle exceptions that may be thrown from its body, it must use the throws clause for the caller to handle the exceptions public void addCourse(String cid, String ttl) throws SQLException {… st.executeUpdate(sql); // may throw SQLException }

Java Exception Hierarchy ObjectErrorExceptionRuntimeExceptionThrowableAWTErrorLinkageErrorClassNotFoundExceptionNoSuchMethodExceptionArithmeticExceptionArrayStoreException Must be handled

Java Exception Hierarchy You can throw only objects that derive from the Throwable class. Errors: – When a "hard" failure in the virtual machine occurs, the virtual machine throws an Error. – Typical Java programs should not catch Errors and it's unlikely that typical Java programs will ever throw Errors either. Exceptions: – Most programs throw and catch objects that derive from the Exception class. – Exception has a special subclass RuntimeException which is not required to be handled

Runtime Exceptions The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). – An example of a runtime exception is NullPointerException. The Java packages define several RuntimeException classes. You can catch these exceptions just like other exceptions. A method is not required to specify that it throws RuntimeExceptions. The cost of checking for all RuntimeExceptions often outweighs the benefit of catching it. the compiler allows RuntimeExceptions to go uncaught and unspecified.

Exception and Inheritance If a catch is written to catch exception objects of a superclass type, it can also catch all objects of subclasses of that superclass – catch (Exception e) { } would catch almost all exceptions This also allows for polymorphic processing of related exceptions It is a syntax error if a catch that catches a superclass object is placed before a catch that catches an object of a subclass of that superclass

The finally Block The finally block is optional; if it present it must be placed after the last catch block The finally block can be used to control resource leaks try { // may throw exceptions } catch (ExceptionType1 ref) { // exception handling statements } catch (ExceptionType2 ref) { // exception handling statements } finally { // statements // resource release statements }

The finally Block A finally block will be executed (if present) regardless of whether or not any exception is thrown and regardless of whether the exception is handled or not. – If there is no exception, it will be executed after the try block – If there is an exception and it is handled by a handler, it will be executed after the catch is completed – If there is an exception and it is not handled by a catch, it will be executed after the termination of the try block and then the exception is passed to to next level – If there is an exception in a catch block, it will be executed after the catch block terminates and then the exception is passed to next level

printStackTrace() and getMessage() Class Throwable offers a printStackTrace method that prints the method call stack Class Exception inherits the method Two constuctors for Exception public Exception() //accept no parameter public Exception(String str) // accept a string – The str stored in Exception may be queried with method getMessage()

printStackTrace & getMessage() public class ExceptionHandling {public static int quotient(int numerator, int denominator) throws DivideByZeroException {if (denominator == 0) throw new DivideByZeroException(); return numerator / denominator; } public static void main(String[] arg) { try { quotient(100, 0); } catch (DivideByZeroException e) { System.err.println(e.getMessage()); e.printStackTrace(); }

printStackTrace & getMessage() The following will be printed by the program – Printed by getMessage() Divide by Zero – Printed by printStackTrace() DivideByZeroException: Divide by Zero at ExceptionHandling.quotient(ExceptionHandling.java:7) at ExceptionHandling.main(ExceptionHandling.java:15)