[Go to site: main page, start]

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

Java Exception Handling Basics

The document discusses the fundamentals of exception handling in Java, explaining that exceptions are abnormal conditions that occur at runtime and can be managed using keywords like try, catch, throw, throws, and finally. It outlines the hierarchy of exceptions, distinguishing between checked exceptions (subclass of Exception) and unchecked exceptions (subclass of RuntimeException), as well as serious errors (subclass of Error). Additionally, it provides examples of handling exceptions with try-catch blocks and explains the behavior of uncaught exceptions and multiple catch clauses.

Uploaded by

sanketh.s577425
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 views52 pages

Java Exception Handling Basics

The document discusses the fundamentals of exception handling in Java, explaining that exceptions are abnormal conditions that occur at runtime and can be managed using keywords like try, catch, throw, throws, and finally. It outlines the hierarchy of exceptions, distinguishing between checked exceptions (subclass of Exception) and unchecked exceptions (subclass of RuntimeException), as well as serious errors (subclass of Error). Additionally, it provides examples of handling exceptions with try-catch blocks and explains the behavior of uncaught exceptions and multiple catch clauses.

Uploaded by

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

MODULE 4[CHAPTER 2]

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
Exceptions
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 run-time error.
◦ In computer languages that do not support exception handling, errors must be checked and handled manually
through the use of error codes, and so on.
◦ Java’s exception handling avoids these problems and, in the process, brings run-time error management into the
object-oriented world.
◦ 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 user 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.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 2
◦ Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
◦ Program statements that user want to monitor for exceptions are contained within a try
block.
◦ If an exception occurs within the try block, it is thrown.
◦ Users code can catch this exception (using catch) and handle it in some rational manner.
◦ 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 must be executed after a try block completion is put in a finally block.
◦ The general form of an exception-handling block:
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 3
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 after try block ends
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 4
Example
class TryCatchFinallyExample {
public static void main(String[] args) {
try {
[Link]("Inside try block");
int result = 10 / 0; // This will cause ArithmeticException
}
catch (ArithmeticException exOb) {
[Link]("Exception caught: " + exOb);
Inside try block
} Exception caught:
catch (Exception exOb) { [Link]: / by zero
[Link]("General exception caught: " + exOb); Finally block executed: Closing resources.
}
finally {
[Link]("Finally block executed: Closing resources.");
} }}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 5
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.
1. 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.
2. 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. Ex: Stack overflow.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 6
There are two main branches under Throwable:
1. Exception (Problems your program can catch and handle)
◦ Exception represents conditions that a program should try to handle using try–catch.
◦ Types of issues that come under Exception:
◦ Invalid input
◦ File not found
◦ Network errors
◦ User mistakes
◦ Database errors
◦ → RuntimeException (Unchecked exceptions)
◦ This is an important subclass of Exception.
◦ These are exceptions that occur during program execution due to logical errors.
◦ You don’t need to declare or catch them explicitly.
◦ Examples of RuntimeException:
◦ ArithmeticException → division by zero
◦ ArrayIndexOutOfBoundsException → invalid array index
◦ NullPointerException → using a null object
◦ NumberFormatException → invalid string to number conversion
◦ These exceptions are programming mistakes, so Java handles them differently.
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 7
2. Error (Serious problems you cannot fix in code)

◦ Error represents issues that occur in the Java runtime environment, not in the
program logic.
◦ These are not meant to be caught by your program because they are usually
fatal.
◦ Examples of Error:
◦ StackOverflowError → infinite recursion
◦ OutOfMemoryError → JVM runs out of memory
◦ InternalError → JVM internal failure
◦ These are system-level problems, not programmer mistakes.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 8
◦ The top-level exception hierarchy is shown here:

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 9
Uncaught Exceptions:
◦ An "uncaught exception" in Java refers to an exception that is thrown during program execution but is not handled
by any try-catch block within the code. When such an exception occurs, the Java Virtual Machine (JVM) intervenes,
leading to the termination of the thread where the exception occurred and the printing of a stack trace to the
console.
◦ Unchecked Exceptions:
◦ These are typically RuntimeException and its subclasses
(e.g., NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException). They are not checked at
compile time, and while you can handle them with try-catch, you are not required to. If they are not caught, they
become uncaught.
◦ For Example: When the Java run-time system detects the attempt to divide by zero, it constructs a new exception
object and then throws this exception.
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[ ]) {
[Link]();
}}
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 10
◦ This causes the execution of Exc1 to stop, because once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
◦ In this example, the exception is caught by the default handler provided by the Java runtime system.
◦ Any exception that is not caught by your 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:

◦ Here, the class name Exc1, the method name main, the filename, [Link]; and the line number, 4, the bottom of
the stack is main’s line 7, which is the call to subroutine( ), which caused the exception at line 4.
◦ All are included in the simple stack trace.
◦ The type of exception thrown is a subclass of Exception called ArithmeticException, which more specifically
describes what type of error happened.
◦ The stack trace will always show the sequence of method invocations that led up to the error.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 11
EXAMPLE 2
class Exc2 {
public static void main(String args[ ]) {
int[ ] myNumbers = { 10, 20, 30 };

// The array has 3 items:


// Index 0 = 10
// Index 1 = 20
// Index 2 = 30

// WE MAKE A MISTAKE HERE:


// We try to access Index 5, which does not exist.
[Link](myNumbers[5]);
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 12
◦ What happens when you run this?Since we did not write a try-catch block, the Default Handler takes over
immediately.
◦ It stops the program and prints this:PlaintextException in thread "main"
[Link]: Index 5 out of bounds for length 3 at
[Link]([Link])

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 13
Using try and catch:
◦ Whenever, User want to handle an exception manually then try catch block will be
used.
◦ doing so provides two benefits.
1. First, it allows you to fix the error.
2. Second, it prevents the program from automatically terminating.
◦ To guard against and handle a run-time 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.
◦ For Example, the following program includes a try block and a catch clause that
processes the ArithmeticException generated by the division-by-zero error:

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 14
SYNTAX

◦ try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception of type ExceptionType
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 15
class Exc2 {
public static void main(String args[]) {
int d, a;

Division by zero.
try { // monitor a block of code. After catch statement.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
[Link]("Division by zero.");
}

[Link]("After catch statement.");


}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 16
◦ The call to println( ) inside the try block is never executed. Once an exception is thrown, program
control transfers out of the try block into the catch block.
◦ Put differently, catch is not “called,” so execution never “returns” to the try block from a catch.
Thus, the line "This will not be printed." is not displayed.
◦ Once the catch statement has executed, program control continues with the next line in the
program following the entire try / catch mechanism.
◦ 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.
◦ The goal of most well-constructed catch clauses should be to resolve the exceptional condition
and then continue on as if the error had never happened.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 17
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.
◦ User can display this description in a println( ) statement by simply passing the exception as an argument.
◦ For example, the catch block in the preceding program can be rewritten like this:

catch (ArithmeticException e) {
[Link]("Exception: " + e);
◦ a = 0; // set a to zero and continue
}

◦ When this version is substituted in the program, and the program is run, each divide-byzero error displays
the following message:
◦ Exception: [Link]: / by zero

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 18
Multiple catch Clauses:
◦ In some cases, more than one exception could be raised by a single piece of
code.
◦ To handle this type of situation, you 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.
◦ After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 19
Syntax of Multiple
Catch Statements:
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 20
The following example exception types:
class MultipleCatches {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[ ] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);

} catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 21
◦ This program will cause a division-by-zero exception if it is started with no command-line arguments, since a
will equal zero.
◦ It will survive the division if user provide a command-line argument, setting a to something larger than zero.
◦ But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the
program attempts to assign a value to c.
◦ Here is the output generated by running it both ways:
◦ C:\>java MultipleCatches
◦ a=0
◦ Divide by 0: [Link]: / by zero
◦ After try/catch blocks.
◦ C:\>java MultipleCatches TestArg
◦ a=1
◦ Array index oob: [Link]:
◦ Index 42 out of bounds for length 1
◦ After try/catch blocks.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 22
Nested try Statements:
◦ The try statement can be nested.
◦ That is, 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 statements succeeds, or until all of the
nested try statements are exhausted.
◦ If no catch statement matches, then the Java run-time system will handle the
exception.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 23
SYNTAX
try {
// Outer risky code
// ...

try {
// Inner risky code
// ...
} catch (ExceptionType1 e1) {
// Handle specific exception for the inner try block
// ...
}

// More outer risky code


// ...

} catch (ExceptionType2 e2) {


// Handle specific exception for the outer try block
// ...
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 24
class NestTry {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a; // May cause divide by zero
[Link]("a = " + a);
try {
// Nested try block
if (a == 2) {
int c[ ] = {1};
c[42] = 99; // Will generate ArrayIndexOutOfBoundsException
}
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out-of-bounds: " + e);
}
} catch (ArithmeticException e) {
[Link]("Divide by 0: " + e);
}}}
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 25
◦ This program nests one try block within another.
◦ The program works as follows.
◦ When you execute the program with no command line arguments, a divide-by-
zero exception is generated by the outer try block.
◦ Execution of the program with one command-line argument generates a divide-
by-zero exception from within the nested try block.
◦ Since the inner block does not catch this exception, it is passed on to the outer try
block, where it is handled.
◦ If you execute the program with two command-line arguments, an array
boundary exception is generated from within the inner try block.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 26
OUTPUT
C:\>java NestTry
Divide by 0: [Link]: / by zero
C:\>java NestTry One
a=1
Divide by 0: [Link]: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
[Link]:
Index 42 out of bounds for length 1
◦ Nesting of try statements can occur in less obvious ways when method calls are involved.
◦ For example, you can enclose a call to a method within a try block. Inside that method is another try statement.
◦ In this case, the try within the method is still nested inside the outer try block, which calls the method.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 27
throw:
◦ It is possible for user program to throw an exception explicitly, using the throw statement.
◦ The general form of throw is :
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.
◦ There are two ways you can obtain a Throwable object:
❖using a parameter in a catch clause or creating one with the new operator.
◦ The flow of execution stops immediately after the throw statement, any subsequent statements are not
executed.
◦ The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of
exception.
◦ If it does find a match, control is transferred to that statement.
◦ If not, then the next enclosing try statement is inspected, and so on.
◦ If no matching catch is found, then the default exception handler halts the program and prints the stack
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 28
trace.
Sample program that creates and throws an exception:
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
[Link]("Caught inside demoproc.");
throw e; // rethrow the exception
}}
public static void main(String args[]) {
Caught inside demoproc.
try { Recaught: [Link]: demo
demoproc();
} catch (NullPointerException e) {
[Link]("Recaught: " + e);
}}}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 29
◦ The handler that catches the exception rethrows it to the outer handler.
◦ This program gets two chances to deal with the same error.
◦ First, main( ) sets up an exception context and then calls demoproc( ).
◦ The demoproc( ) method then sets up another exception-handling 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: [Link]: demo
◦ The program also illustrates how to create one of Java’s standard exception objects:
◦ throw new NullPointerException("demo");
◦ Here, new is used to construct an instance of NullPointerException.
◦ Many of Java’s built-in run-time exceptions have at least two constructors: one with no parameter and one
that takes a string parameter.
◦ When the second form is used, the argument specifies a string that describes the exception.
◦ This string is displayed when the object is used as an argument to print( ) or println( ).
◦ It can also be obtained by a call to getMessage( ), which is defined by Throwable.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 30
throws:
◦ 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.
◦ General form of a method declaration that includes a throws clause:
```
type method-name(parameter-list) throws exception-list
{
// body of method
}
```
◦ Here, exception-list is a comma-separated list of the exceptions that a method can throw.
◦ First, you need to declare that throwOne( ) throws IllegalAccess

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 31
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
[Link]("Caught " + e);
}
}
Output:
} inside throwOne
caught [Link]: demo

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 32
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 33
◦ Example of throw
void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
[Link]("Eligible to vote");
}
◦ Here, throw creates and throws an exception manually.
◦ Example of throws
◦ void readFile() throws IOException {
◦ FileReader fr = new FileReader("[Link]");
◦ }
◦ Here, throws IOException tells the compiler that this method may throw IOException, and whoever calls
this method must handle it.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 34
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.
◦ This could be a problem in some methods.
◦ For example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exceptionhandling mechanism.
◦ The finally keyword is designed to address this contingency.
◦ 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 an uncaught exception or an
explicit return statement, the finally clause is also executed just before the method returns.
◦ The finally clause is optional. However, each try statement requires at least one catch or a finally clause.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 35
class FinallyDemo {
// 1. procA: Exits via an Exception (Runtime)
static void procA() {
try {
[Link]("inside procA");
// An exception is thrown here
throw new RuntimeException("demo");
} finally {
// This is executed before the exception propagates out of procA
[Link]("procA's finally");
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 36
} finally {
// This is executed before procB returns to the caller
[Link]("procB's finally");
}}
// 3. procC: Exits normally (no exception or explicit return)
static void procC() {
try {
[Link]("inside procC");
} finally {
// This is executed after the try block finishes
[Link]("procC's finally");
}}
// 2. procB: Exits via a normal return statement
static void procB() {
try {
[Link]("inside procB");
// The method returns here
return;

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 37
public static void main(String args[]) {
// Test procA (Throws exception, which is caught)
try {
procA();
} catch (Exception e) {
[Link]("Exception caught: " + [Link]()); inside procA
} procA's finally
Exception caught: demo
// Test procB (Exits via return) inside procB
procB(); procB's finally
inside procC
procC's finally
// Test procC (Exits normally)
procC();
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 38
Java’s Built-in Exceptions
◦ Inside the standard package [Link], Java defines several exception classes.
◦ The most general of these exceptions are subclasses of the standard type RuntimeException.
◦ These exceptions need not be included in any method’s throws list.
◦ In the language of Java, these are called unchecked exceptions because the compiler does not check to see if
a method handles or throws these exceptions.
◦ The unchecked exceptions defined in [Link] are listed in Table 10-1.
◦ Table 10-2 lists those exceptions defined by [Link] that must be included in a method’s throws list if that
method can generate one of these exceptions and does not handle it itself.
◦ These are called checked exceptions.
◦ In addition to the exceptions in java. lang, Java defines several more that relate to its other standard packages.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 39
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 40
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 41
Creating Your Own Exception Subclasses
◦ Although Java’s built-in exceptions handle most common errors, user will
probably want to create your own exception types to handle situations specific to
your applications.
◦ This is done by defining a subclass of Exception (which is, a subclass of
Throwable).
◦ The Exception class does not define any methods of its own. It does, inherit
those methods provided by Throwable.
◦ Thus, all exceptions, including those that user create, have the methods defined by
Throwable available to them. They are shown in Table 10-3.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 42
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 43
◦ Exception defines four public constructors:Two support chained [Link] other two are : Exception( ),
Exception(String msg)
◦ The first form creates an exception that has no description.
◦ The second form lets user specify a description of the exception.
◦ Sometimes it is override using toString( ): The version of toString( ) defined by Throwable (and inherited by
Exception) first displays the name of the exception followed by a colon, which is then followed by
description.
◦ By overriding toString( ), you can prevent the exception name and colon from being displayed. This makes
for a cleaner output, which is desirable in some cases.
◦ The following example declares a new subclass of Exception and then uses that subclass to signal an error
condition in a method. It overrides the toString( ) method, allowing a carefully tailored description of the
exception to be displayed.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 44
// Define a custom checked exception
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
// Override toString() to provide a custom description for the exception
public String toString() {
return "MyException[" + detail + "]";
}
}

class ExceptionDemo {
// Declares that this method can throw MyException (a checked exception)

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 45
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if (a > 10) {
// Throw the custom exception if the condition is met
throw new MyException(a);
}
[Link]("Normal exit");
}
public static void main(String args[]) {
try {
// First call: a=1 (Normal exit)
compute(1);
// Second call: a=20 (Throws exception)
compute(20);
} catch (MyException e) {
// Catch block handles the custom exception
[Link]("Caught " + e);
}}}
PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 46
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
This example defines a subclass of Exception called MyException.
This subclass has only a constructor plus an overridden toString( ) method that displays the value of the
exception.
The ExceptionDemo class defines a method named compute( ) that throws a MyException object.
The exception is thrown when compute( )’s integer parameter is greater than 10.
The main( ) method sets up an exception handler for MyException, then calls compute( ) with a legal value
(less than 10) and an illegal one to show both paths through the code.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 47
Chained Exceptions
◦ The chained exception feature allows user 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.
◦ Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you
might also want to let the calling code know that the underlying cause was an I/O error.
◦ Chained exceptions let you handle this, and any other situation in which layers of exceptions exist.
◦ 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)

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 48
◦ In the first form, causeExc is the exception that causes the current exception. That is, causeExc is the
underlying reason that an exception occurred.
◦ The second form allows you to specify a description at the same time that you specify a cause exception.
◦ These two constructors have also been added to the Error, Exception, and RuntimeException classes.
◦ The chained exception methods supported by Throwable are getCause( ) and initCause(
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. The initCause( ) method associates causeExc with the
invoking exception and returns a reference to the exception.
◦ Thus, you can associate a cause with an exception after the exception has been created.
◦ However, the cause exception can be set only once.
◦ This means user can call initCause( ) only once for each exception object.
◦ initCause( ) is used to set a cause for legacy exception classes that don’t support the two additional
constructors.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 49
◦ Here is an example that illustrates the mechanics of handling chained exceptions:
class ChainExcDemo {
static void demoproc() {
// Create top-level exception
NullPointerException ex = new NullPointerException("top layer");
// Set the cause of the exception
[Link](new ArithmeticException("cause"));
// Throw the exception
throw ex;
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 50
public static void main(String args[]) {
try {
demoproc();
}
catch (NullPointerException ex) {
[Link]("Caught: " + ex);
[Link]("Original cause: " + [Link]());
}
}
}

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 51
Output:
Caught: [Link]: top layer
Original cause: [Link]: 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( ).
Chained exceptions can be carried on to whatever depth is necessary. Thus, the cause exception can, itself, have
a cause.

PREPARED BY- [Link] BARIK .ASST. PROFESSOR, DEPT OF CSE, SIR MVIT 52

You might also like