Exception Handling in Java. 2 6.0 Exception Handling Introduction: After completing this chapter,...

22
Exception Handling Exception Handling in Java in Java

Transcript of Exception Handling in Java. 2 6.0 Exception Handling Introduction: After completing this chapter,...

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

Exception Handling in JavaException Handling in Java

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

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

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

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..

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

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

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

5

Exception Handling Hierarchy

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

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

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

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.

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

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

}

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

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

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

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

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

11

Hands-on

• HANDS ON SESSION A

For Throw – Refer 3.6.1 in Hands On document.

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

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.

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

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 …. ; }

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

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

}}

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

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

….. }

}}

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

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 zeroat 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();}

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

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

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

18

Hands-on

• HANDS ON SESSION A

For Re-throwing exceptions – Refer 3.6.2 and 3.6.3 in Hands On document.

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

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

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

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

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

21

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

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?