Index Exception handling Exception In Java Exception Types

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: 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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
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.
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.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
EXCEPTION HANDLING.
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.
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.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
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.
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.
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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.
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.
COMPSCI 230 S Programming Techniques
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
OBJECT ORIENTED PROGRAMMING
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.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Index Exception handling Exception In Java Exception Types Uncaught Exception Throw Finally Customized Exception

Exception handling An exception is an abnormal condition that arises in a code sequence at run time. An exception is a runtime error. In computer languages that do not support exception handling, errors must be checked and handled manually—typically through the use of error codes A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.

Exception in java When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. The method may choose to handle the exception itself, or pass it on. At some point, the exception is caught and processed. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

try { // block of code to monitor for errors } Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 Your code can catch this exception (using catch) and handle it in some rational manner. Refer:ExceptionApplication

To manually throw an exception, use the keyword throw. System-generated exceptions are automatically thrown by the Java runtime system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause finally { // block of code to be executed before try block ends } Any code that absolutely must be executed before a method returns is put in a finally block. If the array size is zero,we can throw that as exception

Exception Types All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception the other is Error.

Exception :- This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.

Error:- The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

Uncaught Exceptions class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; }} When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven't supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Although the default exception handler provided by the Java run-time system is useful for debugging, following are the benefits of doing it by the programmer It allows the programmer to fix the error. Prevents the program from automatically terminating.

Using try and catch Previous program terminated since we didn't handle the exception. public class ExceptionApplication { public static void main(String[] args) { int divident=12; int divisor=0; int quotient=0; System.out.println("in division class "); try{ quotient =divident/divisor; System.out.println("unreachable comment"); }catch(ArithmeticException e){ System.out.println("from cactch block : "); e.printStackTrace(); } System.out.println("After catch block : "+quotient);

The call to println() inside the try block is never executed. Once an exception is thrown , program control transfers out of the try block into the catch block displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism. A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement.

Displaying Exception Exception description can be printed using println( ) statement by simply passing the exception as an argument catch block in the preceding program can be rewritten like this: Training2\com\mes\training\exceptions\HandleError.java catch (ArithmeticException e) { System.out.println("Exception: " + e); divisor =6; // set divisor to a non zero value and continue }

Multiple Catch Clauses Single piece of code can raise more that one type of exception in this situation we can specify more catch clauses , each catching different exception When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their super classes. This is because a catch statement that uses a super class will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its super class. (In Java, unreachable code is an error) Refer : ExceptionMultipleCatch.java

Nested try Statements A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match . This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception Ref:ExceptionNestedTry2.java

throw It is possible for the program to throw an exception explicitly, using the throw statement throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected If no matching catch is found, then the default exception handler halts the program and prints the stack trace Refer : ExceptionThrow.java

ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } public static void main(String args[]) { demoproc(); System.out.println("Recaught: " + e);

Here, new is used to construct an instance of NullPointerException . All of Java's built-in run-time exceptions have two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.

throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception This can be done using throws clause. A throws clause lists the types of exceptions that a method might throw Ref : ExceptionThrows.java

// This program contains an error and will not compile // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne();

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);

finally When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method If a method opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.

Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause. Ref: ExceptionFinally.java

Java's Built-in Exceptions Inside the standard package java.lang , Java defines several exception classes The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available need not be included in any method's throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in java.lang are listed in Table Those exceptions defined by java.lang that must be included in a method's throws list if that method can generate one of these exceptions and does not handle it itself _checked exceptions. Java defines several other types of exceptions that relate to its various class libraries.

Unchecked Exceptions

Customized exceptions To create customized exception define a subclass of Exception. The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. All exceptions, including those that you create, have the methods defined by Throwable available to them. They are shown in below table Ref: UserexceptionApplication.java