06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.

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 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.
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.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
 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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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 Software Solutions Foundations of Program Design Sixth Edition
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.
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.
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.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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 Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
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/
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.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Tirgul 13 Exceptions 1.
Introduction Exception handling Exception Handles errors
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.
ATS Application Programming: Java Programming
Exception Handling and Reading / Writing Files
Web Design & Development Lecture 7
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

06 Exception Handling

2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement Unhandled Exceptions Handling Exceptions throw and throws Statements Propagating Exceptions

3 Objectives Define exception Learn how Java handles exceptions Know the type of exceptions Discuss the Exception Hierarchy Learn to use try-catch()-finally statement Learn to use throw and throws statements Learn how to propagate exceptions

4 What is an Exception? An event during program execution that prevents the program from continuing normally An error condition that changes the normal flow of control in a program A signal that some unexpected condition has occurred in the program

5 Handling Exceptions in Java Exception mechanism is built around the throw-and-catch paradigm “to throw” means an exception has occurred “to catch” means to deal with an exception If an exception is not caught, it is propagated to the call stack until a handler is found Propagating an exception is called “ducking” the exception, or “passing the buck”

6 Types of Exceptions All exceptions in Java are objects of Throwable class Unchecked Exceptions are exceptions derived from Error and RuntimeException classes are usually irrecoverable and not handled explicitly are not checked by the compiler Checked Exceptions are exceptions derived from Exception class excluding the RuntimeException class must be handled explicitly are checked by the compiler Both checked and unchecked exceptions can be thrown and caught New exceptions are created by extending the Exception class or its subclasses

7 Exception Hierarchy Throwable ErrorException RuntimeException InterruptedException ArithmeticException NullPointerException IOException... Unchecked Exceptions Checked Exceptions

8 try-catch()-finally try { /* * some codes to test here */ } catch (Exception1 ex) { /* * handle Exception1 here */ } catch (Exception2 ex) { /* * handle Exception2 here */ } catch (Exception3 ex) { /* * handle Exception3 here */ } finally { /* * always execute codes here */ } try block encloses the context where a possible exception can be thrown each catch() block is an exception handler and can appear several times finally block is always executed before exiting the try statement. finally block is optional but must appear once after the catch() blocks at least one catch() block or finally block must appear in the try statement Exception1 should not shadow Exception2 which in turn should not shadow Exception3 (based on the exception hierarchy)

9 Unhandled Exceptions public class GradingSystem { public static void main(String[] args) { GradingSystem gs = new GradingSystem(); gs.checkGrades(); } void checkGrades() { int[] grades=null; for (int i=0; i<grades.length; i++) { /* test here*/ }; } } Exception in thread "main" java.lang.NullPointerException at codesnippets.GradingSystem.checkGrades(GradingSystem.java:31 ) at codesnippets.GradingSystem.main(GradingSystem.java:6)

10 Handling Exceptions public class GradingSystem { public static void main(String[] args) { GradingSystem gs = new GradingSystem(); gs.checkGrades(); } void checkGrades() { int[] grades=null; try { for (int i=0; i<grades.length; i++) { /* test here*/ }; } catch (NullPointerException e) { System.out.println("Grades may be empty!"); } catch (RuntimeException e) { System.out.println("Problem while executing!"); } catch (Exception e) { System.out.println("Error in checking grades!"); } finally { System.out.println("Finished checking grades."); } } } Grades may be empty! Finished checking grades.

11 throw and throws void validate() throws Exception3 { try { // throw an exception throw new Exception3(); } catch (Exception1 ex) { /* * handle Exception1 here */ } catch (Exception2 ex) { /* * handle Exception2 here */ } catch (Exception3 ex) { /* * can't handle Exception3, * propagate to call stack */ throw new Exception3(ex); } throws clause declares the unhandled exceptions that a method can throw. It propagates the exception to the calling method. It becomes part of the method public interface throw statement explicitly throws an exception throw statement propagates (rethrows) a caught exception Any code that calls this method must handle the exception declared in the throws clause

12 Propagating Exceptions public class GradingSystem { public static void main(String[] args) { GradingSystem gs = new GradingSystem(); try { gs.checkGrades(); } catch (Exception e) {// must handle the exception thrown System.out.println(e.getMessage()); } } void checkGrades() throws Exception { int[] grades={81,0,75}; try { for (int i=0; i<grades.length; i++) { if (grades[i]<=0) throw new Exception("Invalid grade!"); } } catch (NullPointerException e) { System.out.println("Grades may be empty!"); } catch (RuntimeException e) { System.out.println("Problem while executing!"); } catch (Exception e) { System.out.println("Can't handle error here! Rethrowing..."); throw new Exception(e); } }} Can't handle error here! Rethrowing... java.lang.Exception: Invalid grade!

13 Key Points Exceptional conditions sometimes occur in properly written code and must be handled Exception handling in Java is build around the “throw-and-catch” paradigm If a method can’t handle the exception, it can propagate the exception to the call stack All exceptions are objects of Throwable class Only Checked exceptions must be handled explicitly try-catch()-finally statement is the exception handling mechanism of Java throw statement manually creates an exception or rethrows an exception throws statement allows propagation of exception to the call stack