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

Module4opp Part3

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)
14 views

Module4opp Part3

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/ 23

MODULE 3

CHAPTER 2 -Exception Handling


Exception-Handling

• an exception is a run-time error.


• languages that do not support exception handling, errors must be checked and handled
manually—typically through the use of error codes, and so on.
• Java’s exception handling avoids handling problems manually and, in the process, brings
run-time error management into the object oriented world.

Exception-Handling Fundamentals

• A Java exception is an object that describes an exceptional (that is, error) 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.
• That method may choose to handle the exception itself, or pass it on.
• Either way, at some point, the exception is caught and processed.
• Exceptions can be generated by the Java run-time system,
• or they can be manually generated by your code.
• Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
• Briefly, here is how they work. Program statements that create exceptions are contained
within a try block.
• If an exception occurs within the try block, it is thrown.we can catch this exception
(using catch) 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 after a try block completes is put in a finally
block.

This is the general form of an exception-handling block:


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
Page 1
}
// ...
finally {
// block of code to be executed after try block ends
}
• Here, ExceptionType is the type of exception that has occurred.

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. This class is used for exceptional conditions that
user programs should catch.
• 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.
• 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

. This program includes an expression that intentionally causes a divide-by-zero error:


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.
• Here we don’t have 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 our 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.
• Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

Page 2
Using try and catch

• Although the default exception handler provided by the Java run-time system is useful for
debugging,we should handle an exception ourself.
• Doing so provides two benefits.
• First, it allows you to fix the error.
• Second, it prevents the program from automatically terminating.
• To handle a run-time error, simply enclose the code inside a try block.
• Immediately following the try block, include a catch clause that specifies the exception
type to catch

class Exc2
{
public static void main(String args[])
{
int d, a;

try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

Page 3
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.

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

Multiple catch Clauses

• more than one exception could be raised by a single piece of code.


• To handle this type of situation, we 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.

The following example traps two different exception types:

// Demonstrate multiple catch statements.

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

Page 4
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

output:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}

Page 5
catch(ArithmeticException e)
{
System.out.println("This is never reached.");
}
}
}

• If this program is compiled , we will receive an error message stating that the second
catch statement is unreachable because the exception has already been caught.
• Since ArithmeticException is a subclass of Exception, the first catch statement will
handle all Exception-based errors, including ArithmeticException.
• This means that the second catch statement will never execute. To fix the problem,
reverse the order of the catch statements.

Nested try Statements

• The try statement can be nested. That is, a try statement can be inside the block of
another try.

Nested try block :


The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
Page 6
}
catch(Exception e)
{
}
....
Example :

class Excep
{
public static void main(String args[]){
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}

Try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{
System.out.println("handeled");
}

Page 7
System.out.println("normal flow..");
}
run:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
handeled
normal flow..

throw
• it is possible for your program to throw an exception explicitly, using the throw
statement.
• The general form of throw is shown here:
throw ThrowableInstance;
• Here, 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.

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

• First, main( ) sets up an exception context and then calls demoproc( ).


• The demoproc( ) method then sets up another exceptionhandling context and
immediately throws a new instance of NullPointerException, which is caught on the
next line.
• The exception is then rethrown.
• Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

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.
• We can do this by including a throws clause in the method’s declaration.
• A throws clause lists the types of exceptions that a method might throw
.
• This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}

class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}

Page 9
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo

finally
• 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

class FinallyDemo
{
static void procA()
{
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
Finally
{
System.out.println("procA's finally");
}
}

static void procB()


{
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
}
}

static void procC()


{
try {

Page 10
}
Finally System.out.println("inside procC");
{

}
} System.out.println("procC's finally");

public static void main(String args[])

{
try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}
• Here is the output generated by the preceding program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally

Page 11
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
• if the method can generate one of these exceptions and does not handle it itself. These are
called checked exceptions.

Java’s Unchecked RuntimeException

Subclasses Defined in java.lang Exception


Meaning

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on
an unlocked thread.
IllegalStateException Environment or application is in incorrect
state.
NullPointerException Invalid use of a null reference.

• Java’s Checked Exceptions Defined in java.lang

ClassNotFoundException Class not found.


CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract
class or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Page 12
Creating Your Own Exception Subclasses
• It is possible to create to create our own exception types to handle situations specific to
your applications.
• just define a subclass of Exception
• Your subclasses don’t need to actually implement anything—it is their existence in the
type system that allows you to use them as exceptions.
• The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable.
• Thus, all exceptions, including those that we create, have the methods defined by
Throwable available to them.

Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a
completed stack trace
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception, null
is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace, one
element at a time, as an array of

Chained Exceptions

• The chained exception feature allows you to associate another exception with an
exception.
• This second exception describes the cause of the first exception.
• For example, imagine a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero.
• However, the actual cause of the problem was that an I/O error occurred, which caused
the divisor to be set improperly.
• To allow chained exceptions, two constructors and two methods were added to
Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
• These two constructors have also been added to the Error, Exception, and
RuntimeException classes.
• The chained exception methods added to Throwable are getCause( ) and initCause( ).
• These methods are shown
Throwable getCause( )
Throwable initCause(Throwable causeExc)
• The getCause( ) method returns the exception that underlies the current exception. If
there is no underlying exception, null is returned.

Page 13
• The initCause( ) method associates causeExc with the invoking exception and returns a
reference to the exception.

class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e =
new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
The output from the program is shown here:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
• In this example, the top-level exception is NullPointerException.
• To it is added a cause exception, ArithmeticException. When the exception is thrown
out of demoproc( ), it is caught by main( ).
• There, the top-level exception is displayed, followed by the underlying exception, which
is obtained by calling getCause( ).

******************************************************************************
uncaught Exception
public class Exec0
{

Page 14
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

try and catch


public class Exec2
{
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(e);
}
System.out.println("After catch statement.");
}
}
multiple Catch
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = 0;
System.out.println("a = " + a);
int b = 42 / a;
int c[ ] = new int[5] ;
c[6] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);

Page 15
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Nested try
public class NestedTry
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}

try

{
int a[]=new int[5]; a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handeled");
}

System.out.println("normal flow..");
}

}
Page 16
throw example1 :

import java.util.Scanner;

public class ThrowDemo


{
public static void main(String[] args)
{
try
{
Scanner s=new Scanner(System.in);
System.out.println("enter the date");
int d=s.nextInt();

if(d<0 ||d>31)
{
throw new IllegalArgumentException("invalid date");
}
}
catch(IllegalArgumentException e)
{
System.out.println("reason "+e);
}
}
}

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

throw example 3:
class Throw2
{
void checkAge (int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}

public static void main(String args[])


{
Throw2 obj = new Throw2();
obj.checkAge(21);

Page 18
System.out.println("End Of Program");
}
}

throws example 1:
class Throws1
{
public static void main(String args[])
{
try
{
process( );
}
catch(IllegalAccessException e)
{
System.out.println("caught : "+e);
}

static void process( ) throws IllegalAccessException


{
throw new IllegalAccessException("access denied");

}
}

Throws example 2:
import java.io.*;
class Throws2
{
static void m1() throws IOException
{
throw new IOException("device error");//checked exception
}

static void m2()


{
throw new ArithmeticException("divide by zero");
}

public static void main(String args[])

Page 19
{
try
{
m2();
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
m1();
}
catch(IOException e)
{
System.out.println(e);
}

System.out.println("normal flow...");
}
}

Example of finally block


class FinallyBlock
{
static void procA()
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally
{
System.out.println("procA's finally");
}
}

static void procB()


{
try
{
System.out.println("inside procB");
return;
}

Page 20
finally
{
System.out.println("procB's finally");
}
}

static void procC()


{
try
{
System.out.println("inside procC");
}
finally
{
System.out.println("procC's finally");
}
}
public static void main(String args[])
{
try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}

User Defined Exception example 1:

class MyException extends Exception


{
String str1;
MyException(String str2)
{
super(str2);
}
}

class UserDefinedException
{

Page 21
public static void main(String args[])
{
try
{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}

User Defined Exception 2 :


class InvalidProductException extends Exception
{
public InvalidProductException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

class UserDefinedException1
{
static void productCheck(int weight) throws InvalidProductException
{
if(weight<100)
{
throw new InvalidProductException("Product Invalid");
}
}

public static void main(String args[])


{
try
{
productCheck(60);
}
catch (InvalidProductException ex)
{
System.out.println("Caught the exception");

Page 22
System.out.println(ex.getMessage());
}
}
}

Chained Exception
class ChainedException
{
public static void main(String[] args)
{
try
{
// Creating an exception
ArithmeticException ex = new ArithmeticException("Exception");

// Setting a cause of the exception


ex.initCause(new ArithmeticException( "denominator value is 0 that is the actual cause
of the exception"));

// Throwing an exception with cause.


throw ex;
}

catch(ArithmeticException ex)
{
// displaying the exception
System.out.println(ex);

// Getting the actual cause of the exception


System.out.println(ex.getCause());
}
}
}
***************************************************************************

Page 23

You might also like