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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Index Exception handling Exception In Java Exception Types
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
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.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
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.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
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
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
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.
1 cuberoot /* Solve f(x) = x*x*x-5 = 0 f'(x) = 3x^2 */ public class cuberoot{ public static void main(String args[]){ double error= ; double x0.
Unit Types of errors Compile-time errors Run-time errors.
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 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. Agenda Exception. Handling Exceptions. The finally Clause.
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.
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.
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.
Chapter 10 – Exception Handling
COMPSCI 230 S Programming Techniques
Advanced Programming Behnam Hatami Fall 2017.
UNIT-4.
EXCEPTION HANDLING OR ERROR HANDLING.
OBJECT ORIENTED PROGRAMMING
Exception Handling Chapter 9 Edited by JJ.
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.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Exception Handling.
Presentation transcript:

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 exception handling, errors must be checked and handled manually. A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.

Introduction When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method

Introduction Five constructs are used in exception handling: 1) try – a block surrounding program statements to monitor for exceptions 2) catch – together with try, catches specific kinds of exceptions and handles them in some way 3) finally – specifies any code that absolutely must be executed whether or not an exception occurs 4) throw – used to throw a specific exception from the program 5) throws – specifies which exceptions a given method can throw

Introduction try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } //... finally { // block of code to be executed after try block ends }

Exception Types

Uncaught Exceptions class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } O/P: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

Uncaught Exceptions When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. Once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. If no exception handlers are provided, then the exception is caught by the default handler provided by the Java run-time system.

Stack Trace Ex: class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); }} O/P: java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)

Using try and catch Handling the exception has two benefits First, it allows you to fix the error. Second, it prevents the program from automatically terminating. Enclose the code that you want to monitor inside a try block. Following the try block, include a catch clause that specifies the exception type that you wish to catch.

Using try and catch class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); }} O/P: Division by zero. After catch statement.

Displaying a Description of an Exception Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception. catch (ArithmeticException e) { System.out.println("Exception: " + e); a = 0; // set a to zero and continue }

Multiple catch Clauses When more than one exception could be raised by a single piece of code, you can specify two or more catch clauses, each catching a different type of 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.

Multiple catch Clauses class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); }}

Multiple catch Clauses When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. In Java, unreachable code is an error.

Multiple catch Clauses try { ….. } catch(Exception e) { System.out.println("Generic Exception catch."); } catch(ArithmeticException e) { System.out.println("This is never reached."); }

Nested try Statements class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { // nested try block if(a==1) a = a/(a-a); // division by zero if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }

Nested try Statements C:\>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:\>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException:42

Throw Programs can throw an exception explicitly. throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a parameter in a catch clause, or creating one with the new operator

Throw 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 exception. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

Throw Example // Demonstrate throw. class 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[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } }}

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. Athrows clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.

Throws type method(args-list) throws exception-list { // body of method } exception-list is a comma-separated list of the exceptions that a method can throw.

Throws Example // This is now correct. 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); } }} O/P: inside throwOne caught java.lang.IllegalAccessException: demo

finally When an exception is thrown: 1) the execution of a method is changed 2) the method may even return prematurely 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. Finally block example.

finally The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Finally Example

Unchecked Built-In Exceptions These exceptions are subclasses of the standard type RuntimeException. Methods that generate but do not handle those exceptions need not declare them in the throws clause Compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in java.lang package.

Unchecked Built-In Exceptions

Checked Built-In Exceptions Methods that generate but do not handle those exceptions must declare them in the throws clause:

Creating Own Exception Classes Built-in exception classes handle some generic errors. For application-specific errors define your own exception classes. Define a subclass of Exception: class MyException extends Exception { … } MyException need not implement anything – its mere existence in the type system allows to use its objects as exceptions.

Example: Own Exceptions 1 A new exception class is defined, with a private detail variable, a one parameter constructor and an overridden toString method: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; }}

Example: Own Exceptions 1 class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } }}

Thank You