0% found this document useful (0 votes)
2 views31 pages

Oop Using Java - Unit V

This document provides an overview of exception handling in Java, explaining the fundamentals of exceptions, the keywords used for handling them (try, catch, throw, throws, finally), and the hierarchy of exception classes. It also covers how to create custom exceptions, handle multiple exceptions, and the importance of using exceptions for error management in Java programs. Additionally, it discusses recent features like try-with-resources and multi-catch for improved exception handling.

Uploaded by

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

Oop Using Java - Unit V

This document provides an overview of exception handling in Java, explaining the fundamentals of exceptions, the keywords used for handling them (try, catch, throw, throws, finally), and the hierarchy of exception classes. It also covers how to create custom exceptions, handle multiple exceptions, and the importance of using exceptions for error management in Java programs. Additionally, it discusses recent features like try-with-resources and multi-catch for improved exception handling.

Uploaded by

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

Object Oriented

Programming using Java


Unit - V: Exception Handling
Exception-Handling Fundamentals
● An exception is an abnormal condition that arises in a code sequence at run
time.
● In other words, an exception is a runtime error.
● 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 runtime 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.
Exception Handling Fundamentals
● Java Exception handling is managed via five keywords
○ try
○ catch
○ throw
○ throws
○ finally
● Program statements that you want to monitor for exceptions are
contained within a try block.
● If an exception occurs within the try block, it is thrown. Your code
can catch this exception(using catch) and handle it in some
rational manner.
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 before try
block ends
}
Exception Types
● All exception types are subclasses of the builtin class Throwable.
● 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, which is used for exceptional conditions
that user programs should catch. also, the class that you will subclass to
create your own custom exception types.
○ the other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
Uncaught Exceptions
● When the java runtime 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
public class Exc0 {
public static void main(String[] args) { int d
= 0;
int a = 42 / d;
}
}
● 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

java.lang.ArithmeticException: / by

zero at

Exc0.main(Exc0.java: 4)
Using try and catch
● Although the default exception handler provided by the Java
runtime system is useful for debugging, you will usually want to
handle an exception yourself.
● Two benefits:
○ First, it allows you to fix the error
○ Second, it prevents the program from automatically terminating.
● To guard against and handle a runtime error, simply enclose the
code that you want to monitor inside a try block.
● Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch.
public 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.");
}
}
Handle an exception and move on

import java.util.Random;

public class HandleError {


public static void main(String[] args)
{ int a = 0, b = 0, c = 0;
Random r = new Random();

for (int i = 0; i < 32000; i++) {


try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b / c);
} catch (ArithmeticExceptione) {
System.out.println("Division by
zero."); a = 0; // set a to zero and
continue
}
System.out.println("a: " + a);
}
}
}
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.
● You can display this description in a println() statement by simply
passing the exception as an argument.
Multiple catch clauses
● 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.
● After one catch statement executes, the others are bypassed, and
execution continues after the try / catch block.

public class MultipleCatches {


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 ("Division by zero: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System .out .println ("Array index oob: " +
e);
}
System .out .println ("After try/catch blocks." );
}
}
/* This program contains an error.

A subclass must come before its superclass in


a series of catch statements. If not,
unreachable code will be created and a
compile-time error will result.
*/

public 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." );
}
// This catch is never reached because
// ArithmeticException is a subclass of Exception.
// catch (ArithmeticException e) { // ERROR - unreachable
// System.out.println("This is never reached.");
// }
}
}
Nested try statements
● the try statement can be nested.
● a try statement can be inside the block of another try
● each time a try statement is entered, the context of that
exception is pushed on the stack.
● if an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
● this continues until one of the catch statement succeeds or
until all of the nested try statements are exhausted.
● if no catch statement matches, then the java runtime system will
handle the exception.
public class NestTry {
public static void main (String [] args ) { try {
int a = args .length ;

/*
* If no command line args are present, the following statement will generate a
* divide-by-zero exception.
*/
int b = 42 / a;

System .out.println ("a = " + a);

try { // nested try block


/*
* If one command line arg is used, then an out-of-bounds exception will be
* generated by the following statement.
*/
if (a == 1)
a = a / (a - a); // division by zero

/*
* If two command line args are used, then generate an out-of-bounds exception.
*/
if (a == 2) { int[] c = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) { System
.out.println ("Array index oob: " + e);
}
} catch (ArithmeticException e) {
System .out.println ("Division by zero: " + e);
}
}
}
public class MethNestTry {
static void nesttry (int a) { public static void main(String[] args) {
try { // nested try block try {
/* int a = args.length;
* If one command line arg is used, then an out-of-bounds
exception will be
/*
* generated by the following statement.
*/ * If no command line args are present, the
if (a == 1) following statement will generate a
a = a / (a - a); // division by zero * divide-by-zero exception.
*/
/*
int b = 42 / a;
* If two command line args are used, then generate an
out-of-bounds exception.
System.out.println("a = " + a);
*/
if (a == 2) {
int [] c = { 1 }; nesttry(a);
c[42] = 99; // generate an out-of-bounds exception } catch (ArithmeticException e) {
} System.out.println("Division by zero: " +
} catch (ArrayIndexOutOfBoundsException e) {
e);
System .out .println ("Array index oob: " +
}
e);
}
}
} }
throw
● It is possible for your program to throw an exception explicitly,
using the throw statement.
public 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.
● You 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 necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses.
● All other exceptions that a method can throw must be declared in
the throws clause. If they are not, a compile-time error will result.
public 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);
}
}
}
finally
● when exceptions are thrown, execution in a method takes a
rather abrupt, nonlinear path that alters the normal flow
through the method.
● depending upon how the method is coded, it is even possible for an
exception to cause the method to 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.
● if an exception is thrown, the finally block will execute even
if no catch statement matches the exception.
● any time a method is about to return to the caller from inside a
try / catch block, via n uncaught exception or an explicit return
statement.
public class FinallyDemo {
// Execute a try block normally.
// Throw an exception out of the method.
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");
}
}
}
public static void main(String[] args) {
try {
// Return from within a try block.
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");
}
}
}
}
Java Built-in Exceptions

Arithmetic Exception: Arithmetic error, such as divide-by-zero.


Array Index Out Of Bounds Exception: Array index is out-of-bounds.
Array Store Exception: Assignment to an array element of an
incompatible type. Class Cast Exception: Invalid cast.
Enum Constant Not PresentException: An attempt is made to use an undefined
enumeration value. Illegal Argument Exception: Illegal argument used to invoke a method.
Illegal Monitor State Exception: Illegal monitor operation, such as waiting on an
unlocked thread. Illegal State Exception: Environment or application is in incorrect
state.
Illegal Thread State Exception: Requested operation not compatible with current
thread state. Index Out Of Bounds Exception: Some type of index is out-of-bounds.
Negative Array Size Exception: Array created with a
negative size. Null Pointer Exception: Invalid use of a null
reference.
Number Format Exception: Invalid conversion of a string to a numeric
format. Security Exception: Attempt to violate security.
String Index Out Of Bounds Exception: Attempt to index outside the bounds of a
string. Unsupported Operation Exception: An unsupported operation was
encountered.
Type Not Present Exception: Type not found.
Creating your own Exception subclasses
● 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 you create, have the
methods defined by Throwable available to them.
public class ExceptionDemo extends Exception { private int
detail ;

ExceptionDemo (int a) { detail = a;


}

public String toString () {


return "MyException[" + detail + "]" ;
}
}

class ExceptionDemo {
static void compute (int a) throws ExceptionDemo { System .out
.println ("Called compute(" + a + ")" ); if (a >
10) {
throw new ExceptionDemo (a);
}
System .out .println ("Normal exit" );
}

public static void main (String [] args ) { try {


compute (1);
compute (20);
} catch (ExceptionDemo e) {
System .out .println ("Caught " + e);
}
}
}
Chained Exceptions

public 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 ());
}
}
}
Three Recently Added Exception Features
● the first automates the process of releasing a resource, such as a
file when it is no longer needed.
● it is based on an expanded form of the try statement called try with
resources
● the multi-catch feature allows two or more exceptions to be
caught by the same catch clause.
● it is not uncommon for two or more exception handlers to use teh
same code sequence even though they respond to different
exceptions.
public class MultiCatch {
public static void main(String[] args) { int a
= 10, b = 0;
int[] vals = {1, 2, 3};

try {
int result = a / b;
vals[10] = 19;
} catch (ArithmeticException |
ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " +
e);
}
System.out.println("After multi-catch.");
}
}
Using Exceptions
● Exception handling provides a powerful mechanism for
controlling complex programs that have many dynamic runtime
characteristics.
● It is important to think of try, throw and catch as clean ways to
handle errors and unusual boundary conditions in your program’s
logic.
● Unlike some other languages, in which error return codes are used
to indicate failure, Java uses exceptions.
● Thus, when a method can fail, have it throw an exception. This is
a cleaner way to handle failure modes.
End of Unit V: Exception Handling

You might also like