Exception Handling in Java. 2 6.0 Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.

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 CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
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.
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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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. 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. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
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.
CIS 270—Application Development II Chapter 13—Exception Handling.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
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.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
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.
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.
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.
Exceptions in the Java programming language J. W. Rider.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
Introduction Exception handling Exception Handles errors
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
Exception Handling in Java
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.
Exception Handling.
Presentation transcript:

Exception Handling in Java

2 6.0 Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds of exceptions in java and to handle exceptions in in an efficient manner. Objective: After completing this chapter, you will able to, Use exception Handling Hierarchy Explain kinds and nature of Exceptions Differentiate between Throw and Throws Use methods for Handling Exceptions Print Stack Traces Rethrow Exceptions

3 Introduction Exception Handling : –Is a mechanism that allows Java programs to handle various exceptional conditions. –Exception - condition which occurs during program execution which is (usually) indicative of some kind of failure or error condition. –A program can throw an exception explicitly using the throw statement. –After an exception is thrown - control is transferred from the current point of execution to an appropriate catch clause of an enclosing try statement –Catch clause - is the exception handler. –E.g: »attempting to access a file which does not exist, » attempting to convert a non-numeric string to a numeric value etc..

4 Introduction E.g. : try { out.write(b); } catch (IOException e) { System.out.println("Output Error"); } finally { out.close(); } The Finally Block - always executed before control leaves the try statement If the Try clause does not have any catch clause to handle the exception » it propagates up through enclosing statements in the current method Invoking method..goes on till it finds the catch clause to handle the exception, else the thread terminates. The parameter in a catch clause must be of type Throwable or one of its subclasses

5 Exception Handling Hierarchy

6 Java has two kinds of exceptions: – unchecked exception - NOT required to provide code to handle it. – checked exception - MUST provide code to handle or a fatal compiler error will be issued. – If the programmer calls a method which can throw a checked exception, code must be provided to handle that exception Kinds of Exceptions

7 Nature of Exceptions Broadly speaking, there are three different situations that cause exceptions to be thrown: –Exceptions due to programming errors: e.g., NullPointerException and IllegalArgumentException). –Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. –Exceptions due to resource failures: For example: the system runs out of memory or a network connection fails.

8 Throw and Throws ‘throw’ keyword is used to throw the exceptions explicitly. –Syntax for throw: throw ThrowableInstance; ‘throws’ keyword lists the type of exceptions that a method might throw. –Syntax for throws: type method-name(parameter-list) throws exception-list { //body of method }

9 E.g. for Throw : class ThrowDemo { static void demoproc() { try { throw new NullPointerException(“demo”); } catch (NullPointerException e) { System.out.printl(“caught in demoproc”); throw e; } public static void main (String args[]) { try { demoproc(); } catch (NullPointerException e) { System.out.println(“recaught:” + e); } Throw and Throws

10 E.g. for Throws : class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println(“Inside throwOne.”); throw new IllegalAccessException(“demo”); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println(“Caught” + e); } Throw and Throws

11 Hands-on HANDS ON SESSION A For Throw – Refer in Hands On document.

12 Methods for Handling Exceptions Various methods for handling exceptions : –Declaring exceptions : If a method is expected to throw any exceptions, the method declaration must declare that fact in a throws clause. The classes listed in a throws clause must be Throwable or any of its subclasses; The Throwable class is the superclass of all objects that can be thrown in Java. If the exception is an instance of Error, RunTimeException, or a subclass of one of those classes, it does not have to be listed in a throws clause.

13 Methods for Handling Exceptions E.g.: class throwsExample {... // Method explicitly throws an exception int read() throws IOException { if (….) throw new IOException(); return … ; } // Method implicitly throws an exception String readUpTo(….) throws IOException { int c = read(); // Can throw IOException return …. ; }

14 Methods for Handling Exceptions // Method catches an exception internally getLength() { …. try { s = readUpTo(':'); } catch (IOException e) { … … } // Method can throw a RunTimeException getAvgLength() { ……. return total/count; // Can throw ArithmeticException }}

15 Methods for Handling Exceptions Generating Exceptions : For program-defined exceptions: » define a new subclass of Exception that is specific to your program. E.g.: class WrongDayException extends Exception { public WrongDayException () {} public WrongDayException(String msg) { super(msg); }} public class ThrowExample { void doIt() throws WrongDayException{ ……. } public static void main (String [] argv) { try { …….. } catch (WrongDayException e) { ….. } }}

16 Printing Stack Traces Printing Stack Traces: To figure out where the exception came from. A stack trace looks like the following: java.lang.ArithmeticException: / by zero at t.cap(t.java:16) at t.doit(t.java:8) at t.main(t.java:3) printStackTrace() method - prints the stack trace. E.g.: int cap (x) { return 100/x } try { cap(0); } catch(ArithmeticException e) { e.printStackTrace(); }

17 Rethrowing Exceptions Rethrowing Exceptions : E.g. : try { cap(0); } catch(ArithmeticException e) { throw e; } The above code rethrows an exception and has the stack trace indicate the original location fillInStackTrace() method - sets the stack trace information in the exception based on the current execution context. E.g. : try { cap(0); } catch(ArithmeticException e) { throw (ArithmeticException)e.fillInStackTrace(); }

18 Hands-on HANDS ON SESSION A For Re-throwing exceptions – Refer and in Hands On document.

19 An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Two kinds of Exception : Checked Exception UnChecked Exception An exception causes a jump to the end of try block. If the exception occurred in a method called from a try block, the called method is abandoned. If there’s a catch block for the occurred exception or a parent class of the exception, the exception is now considered handled. At least one ‘catch’ block or one ‘finally’ block must accompany a ‘try’ statement. If all 3 blocks are present, the order is important. (try/catch/finally) finally and catch can come only with try, they cannot appear on their own. Regardless of whether or not an exception occurred or whether or not it was handled, if there is a finally block, it’ll be executed always. (Even if there is a return statement in try block). Exception Handling - Summary

20 If the exception is not handled, the process repeats looking for next enclosing try block up the call hierarchy. If this search reaches the top level of the hierarchy (the point at which the thread wascreated), then the thread is killed and message stack trace is dumped to System.err. The method fillInStackTrace() in Throwable class throws a Throwable object. It will be useful when re-throwing an exception or error. Exception Handling - Summary

21

22 Test Your Understanding What is an Exception? What is the difference between Throw and Throws? What happens when an exception is not handled? What is a checked exception? What is necessity to re-throw an exception?