0% found this document useful (0 votes)
4 views21 pages

Lec 16

The document provides an overview of exception handling in Java, explaining the concept of exceptions, how to catch and handle them using try-catch blocks, and the use of keywords like throw, throws, and finally. It details the hierarchy of exception classes and demonstrates how to throw exceptions explicitly. Additionally, it includes examples to illustrate the proper use of exception handling mechanisms in Java programs.

Uploaded by

Atik Shahriar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

Lec 16

The document provides an overview of exception handling in Java, explaining the concept of exceptions, how to catch and handle them using try-catch blocks, and the use of keywords like throw, throws, and finally. It details the hierarchy of exception classes and demonstrates how to throw exceptions explicitly. Additionally, it includes examples to illustrate the proper use of exception handling mechanisms in Java programs.

Uploaded by

Atik Shahriar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Exception Handling

Exceptions
An exception is a condition that is caused by run-time error in
the program
When the java interpreter encounters an error such as…
Dividing an integer by zero
It creates an exception object and throws (i.e., informs us that
an error has occurred)

2
Exception Handling
• If the exception object is not caught and handled properly
• The interpreter will display an error message and will terminate
the program

class excphand
{
public static void main(String args[ ] )
{
int a =10;
int b =5;
int c =5;
int x = a/(b-c);
System.out.println("x = " + x);
int y = a/(b-c);
System.out.println ("y = " + y);
}
} 3
Exception Handling
• If we want the program to continue with the execution of the
running code
• We should try to catch the exception object thrown by the error condition and
then display an appropriate message for taking corrective actions
• This task is known as

class excphand x = a/(b-c);


{ }
public static void main(String args[ ] ) catch (ArithmeticException e)
{ {
int a =10; System.out.println ("Division by zero");
int b =5; }
int c =5; y = a/(b+c);
int x,y; System.out.println ("y = " + y);
Try }
{ }
4
Exception Handling Mechanism
• Java uses a keyword try to prefer a block of code that is
likely to cause an error condition and “throw” an
exception
• A catch block define by the keyword catch “catches” the
exception “thrown” by the try block and handle it
appropriately

5
Exception Handling Mechanism
try Block Exception objet
cause an exception creator

Throws
exception
object

catch Block Exception


handle the exception handler
6
Simple try and catch statement
//……….
try{
// block of code to monitor for errors
//that means generate an exception
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb){
// exception handler for ExceptionType2
}
//…
7
Exception Handling
• Java exception handling is managed by via five keywords
• try
• catch
• throw
• throws
• finally

8
Exception Handling
• try
• Marks the start of a block associated with a set of exception handlers
• Catch
• Receive the error information
• throw
• Inform that an error has occurred
• throws
• Any exception that is thrown out of a method must be specified as
such by a throws clause
• finally
• Always

9
Outlines of Presentation
• Overview of Exception Handling
• The Basic Model
• Hierarchy of Event Classes
• Throw Clauses
• Throws Statement

10
Outlines of Presentation
• Overview of Exception Handling
• The Basic Model
• Hierarchy of Event Classes
• Throw Clauses
• Throws Statement
• Try Catch Block

11
Outlines of Presentation
• Overview of Exception Handling
• The Basic Model
• Hierarchy of Event Classes
• Throw Clauses
• Throws Statement
• Try Catch Block

12
Hierarchy of Exception Classes
• All error and exception classes are descendents or
subclass of the Throwable class
• A programmer can define an exception by extending the
Exception class or one of its descendants
• Example: java.lang.Exception class

• The Exception class has two main subclasses


• IOException class
• RuntimeException Class
• It defined automatically for user programs to include: division by zero,
invalid array indexing, etc

13
Hierarchy of Exception Classes

14
Throwing Exceptions(throw)
• So far, we were only catching the exceptions thrown by
the Java system
• In fact, a user program may throw an exception explicitly:
throw ThrowableInstance;
• ThrowableInstance must be an object of type Throwable
or its subclass
• Exceptions are thrown using the throw statement

15
Throwing Exceptions(throw)
• Two ways to obtain a Throwableinstance
• Creating one with the new operatore
throw new NullPointerException("demo");
• Using a parameter of the catch clause
try { … } catch(Throwable e) { … e …}

16
throws Declaration
• If a method is capable of causing an exception that it does
not handle, it must specify this behavior by the throws
clause in its declaration:
type name(parameter-list) throws exception-list
{

}

17
Example: throws 1
• The throwOne method throws an exception that it
does not catch, nor declares it within the throws
clause
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}

18
Example: throws 2
• Corrected program: throwOne lists exception, main catches it

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

19
Finally clause
• It is used to handle premature execution of a method (i.e. a
method open a file upon entry and closes it upon exit)
• finally creates a block of code that will be executed after
try/catch block has completed
• finally clause will execute whether or not an exception is
thrown
• The try/catch statement requires at least one catch or
finally clause, although both are optional
try { … }
catch(Exception1 ex1) { … } …
finally { … }
20
Example
class demoproc { //In procC, the try statement executes normally
//procA prematurely breaks out of the try by throwing //without error, however the finally clause is still
//an exception, the finally clause is executed on the //executed
//way out static void procC() {
static void procA() { try {
try { System.out.println("inside procC");
System.out.println("inside procA"); } finally {
throw new RuntimeException("demo"); System.out.println("procC's finally");
} finally { }
System.out.println("procA's finally"); }
}}
//Demonstration of the three methods
//procB’s try statement is exited via a return public static void main(String args[]) {
//statement, the finally clause is executed before try {
//procB returns procA();
static void procB() { } catch (Exception e) {
try { System.out.println("Exception caught");
System.out.println("inside procB"); }
return; procB();
} finally { procC();
System.out.println("procB's finally"); }
}} }
21

You might also like