0% found this document useful (0 votes)
2 views

Exception Handling

Oops through java

Uploaded by

vaddivanisri1802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception Handling

Oops through java

Uploaded by

vaddivanisri1802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT-III 2

Example Program:

class NoExceptionHandling
{
public static void main(String args[])
{
int a=10,b=20,c=0;
System.out.println("Before");
a=b+c;
a=b/c;
System.out.println("After");
}
}

UNIT-III 3
Exception Handling Fundamentals:

An exception is a run-time error.

An exception is an event that occurs during the execution of a program that


disrupts the normal flow of instructions.

An exception is an abnormal condition that arises in a code sequence at


run time.

An exception is a representation of an error condition or a situation that is


not the expected result of a method.

UNIT-III 4
Exception Handling Fundamentals:

Exceptions are built into the Java language and are available to all program
code.

A Java exception is an object that describes an exceptional condition that has


occurred in a piece of code

When an exceptional condition arises, an object representing that exception


is created and thrown in the method that caused the error

An exception can be caught to handle it or pass it on

Exceptions can be generated by the Java run-time system, or they can be


manually generated by your code

UNIT-III 5
Exception Handling Fundamentals:
Java exception handling is managed by five keywords:
try
catch
throw
throws
finally

Program statements to monitor are contained within a try block


If an exception occurs within the try block, it is thrown.
Code within catch block catch the exception and handle it.
System generated exceptions are automatically thrown by the Java run-time
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.
Any code that absolutely must be executed before a method returns is put in a
finally block.
UNIT-III 6
Example program: Simple try and catch
class TryDemo
{
public static void main(String args[])
{
int a=10,b=20,c=0; Output:-
System.out.println("Before try");
try
{
a=b+c;
a=b/c;
System.out.println("In try");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
System.out.println("After try");
}
} UNIT-III 7
Example program: Multiple catches
class TryCatchesDemo{
public static void main(String args[ ]) {
int a=10,b=20,c=0;
int n[ ]=new int[5];
System.out.println("Before try");
try Output:-
{
a=b+c;
a=b/c;
n[8]=30;
System.out.println("In try");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("AIOOB Exception caught"+e);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception caught"+e);
}
System.out.println("After try");
}} UNIT-III 8
Example program: Multiple catches
class TryCatchesDemo{
public static void main(String args[ ]) {
int a=10,b=20,c=0;
int n[ ]=new int[5];
System.out.println("Before try");
try Output:-
{
a=b+c;
a=b/c;
n[8]=30;
System.out.println("In try");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("AIOOB Exception caught"+e);
}
System.out.println("After try");
}
}

UNIT-III 9
Nested try Statements:

The try statements can be nested:

If an inner try does not catch a particular exception, the exception is


inspected by the outer try block, this continues until:

a) one of the catch statements succeeds or

b) all the nested try statements are exhausted

In the latter case, the Java run-time system will handle the exception.

UNIT-III 10
Example program: Nested try
class NestedTryDemo1{
public static void main(String args[ ]) {
int a=10,b=20,c=0;
System.out.println("Before try");
try { Output:-
a=b+c;
try {
a=b/c;
System.out.println("In inner try");
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception caught");
}
System.out.println("In outer try");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("AIOOB Exception caught");
}
System.out.println("After try"); UNIT-III 11
}}
Example program: Nested try
class NestedTryDemo2{
public static void main(String args[ ]) {
int a=10,b=20,c=0;
System.out.println("Before try");
try { Output:-
a=b+c;
try {
a=b/c;
System.out.println("In inner try");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(" AIOOB Exception caught");
}
System.out.println("In outer try");
}
catch(ArithmeticException e)
{
System.out.println(" Arithmetic Exception caught");
}
System.out.println("After try"); UNIT-III 12
}}
Exception Sources:

Exceptions can be:

1) generated by the Java run-time system


Fundamental errors that violate the rules of the Java language
or the constraints of the Java execution environment.

2) manually generated by programmer’s code


Such exceptions are typically used to report some error
conditions to the caller of a method.

UNIT-III 13
Throwing Exceptions:
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.

Once an exception is thrown by: throw ThrowableInstance;

1) the flow of control stops immediately

2) the nearest enclosing try statement is inspected if it has a catch


statement that matches the type of exception:
a) if one exists, control is transferred to that statement
b) otherwise, the next enclosing try statement is examined
c) if no enclosing try statement has a corresponding catch clause, the
default exception handler halts the program and prints the stack
UNIT-III 14
Example program: throw

try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception“+e);
}

try try
{ {
throw new NullPointerException("demo"); throw eObj;
} }
catch(NullPointerException e) catch(Exception e)
{ {
System.out.println("Exception“+e); System.out.println("Exception“+e);
} }

UNIT-III 15
finally Clause:

The try statement requires at least one catch or finally clause, although both
are optional:

try { … }
catch(Exception1 ex1) { … } …
finally { … }

Executed after try/catch whether or not the exception is thrown.

Any time a method is to return to a caller from inside the try/catch block via:
1) uncaught exception or
2) explicit return

the finally clause is executed just before the method returns.

UNIT-III 16
Example program: finally
void procA( ) { void procB( ) {
try { try {
System.out.println("inside procA"); System.out.println("inside procB");
throw new RuntimeException("demo"); return;
} }
finally { finally {
System.out.println("procA's finally"); System.out.println("procB's finally");
} }
} }

void procC( ) { void procD( ) {


try { try {
System.out.println("inside procC"); System.out.println("inside procD");
} throw new RuntimeException("demo");
finally { }
System.out.println("procC's finally"); catch(RuntimeException e) {
} System.out.println(“Caught”);
} }
finally {
System.out.println("procD's finally");
} }
UNIT-III 17
Exception Types:
All exceptions are instances of a class extended from Throwable class or its subclass.

Object

Throwable

Error Exception

RunTimeException
LinkageError ArithmeticException
IndexOutOfBoundsException

ThreadDeath StringIndexOutOfBoundsException

IllegalArguementException

VirtualMachineError NumberFormatException

IllegalAccessException
AWTError NoSuchMethodException
UNIT-III
ClassNotFoundException18
Java Exception class hierarchy:

ClassNotFoundException

CloneNotSupportedException
Exception
IOException
ArithmeticException
AWTException
NullPointerException
RuntimeException
Object Throwable IndexOutOfBoundsException

NoSuchElementException
LinkageError

VirtualMachoneError
Error
AWTError
Checked

Unchecked

UNIT-III 19
Exception Types:

Java exceptions fall into two categories.


1. Checked exceptions
2. Unchecked exceptions
When a method throws a checked exception, the compiler checks that you
don’t ignore it.
On the other hand, the compiler does not require you to keep track of
unchecked exceptions.
All subclasses of RuntimeException are unchecked exceptions.

UNIT-III 20
Unchecked Built-In Exceptions:

UNIT-III 21
Unchecked Built-In Exceptions:

UNIT-III 22
Checked Built-In Exceptions:

UNIT-III 23
throws:

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


{

}

where exception-list is a comma-separated list of all types of exceptions


that a method might throw.

All exceptions must be listed, otherwise a compile-time error occurs.

UNIT-III 24
throws: Example program1
class ThrowsDemo {
void m1( ) {
System.out.println("Inside m1.");
throw new IllegalAccessException("demo");
}
void m2( ) {
System.out.println("Inside m2.");
throw new ArithmeticException("demo");
}
public static void main(String args[ ]) {
ThrowsDemo t1=new ThrowsDemo( );
t1.m1( );
t1.m2( );
}
}

UNIT-III 25
throws: Example program1

UNIT-III 26
throws: Example program2
class ThrowsDemo1 {
void m1( ) throws IllegalAccessException {
System.out.println("Inside m1.");
throw new IllegalAccessException("demo");
}
void m2( ) {
System.out.println("Inside m2.");
throw new ArithmeticException("demo");
}
public static void main(String args[ ]) {
ThrowsDemo1 t1=new ThrowsDemo1( );
t1.m1( );
t1.m2( );
}
}

UNIT-III 27
throws: Example program2

UNIT-III 28
throws: Example program3
class ThrowsDemo2 {
void m1( ) throws IllegalAccessException {
System.out.println("Inside m1.");
throw new IllegalAccessException("demo");
}
void m2( ) {
System.out.println("Inside m2.");
throw new ArithmeticException("demo");
}
public static void main(String args[ ]) {
ThrowsDemo2 t1=new ThrowsDemo2( );
try{
t1.m1( );
}
catch(IllegalAccessException e)
{
System.out.println("Exception caught");
}
t1.m2( );
}
}
UNIT-III 29
throws: Example program3

UNIT-III 30
throws: Example program4

class ThrowsDemo3 {
void m1( ) throws IllegalAccessException {
System.out.println("Inside m1.");
throw new IllegalAccessException("demo");
}
void m2( ) {
System.out.println("Inside m2.");
throw new ArithmeticException("demo");
}
public static void main(String args[ ]) throws IllegalAccessException
{
ThrowsDemo3 t1=new ThrowsDemo3( );
t1.m1( );
t1.m2( );
}
}

UNIT-III 31
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.

UNIT-III 32
Creating Own Exception Classes: Example program1
class RangeException extends Exception {
String name;
RangeException(String name1) {
name=name1;
}
public String toString( ) {
return "Exception:"+name+"RangeException";
}
}
class ExceptionDemo {
public static void main(String args[ ]) {
int i=10;
try {
if(i>=10)
throw new RangeException("first");
}
catch(RangeException e) {
System.out.println(e);
}
}
} UNIT-III 33
ChainedExceptions:

The chained exception feature allows you to associate another


exception with an exception.

This second exception describes the cause of the first exception.

To allow chained exceptions, Java 2, version 1.4 added two


constructors and two methods to Throwable.

Constructors:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)

Methods:
Throwable getCause( )
Throwable initCause(Throwable causeExc)

UNIT-V 34
UNIT-III 34
ChainedExceptions: Example program1
class ChainedExceptionsDemo
{
public static void main(String args[])
{
ArithmeticException e=new ArithmeticException();
ArrayIndexOutOfBoundsException a1=new
ArrayIndexOutOfBoundsException();
IllegalAccessException i1=new IllegalAccessException();
e.initCause(a1);
a1.initCause(i1);
try
{
throw e;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
System.out.println(ae.getCause());
System.out.println(ae.getCause().getCause());
}
}
} UNIT-III 35

You might also like