0% found this document useful (0 votes)
31 views38 pages

Ooj Notes 8

The document provides an overview of exception handling in Java. It discusses that exceptions are objects that describe error conditions, and can be generated by the Java runtime system or manually in code. Code that could generate exceptions is placed in a try block, and exceptions can be caught using catch blocks. Finally blocks contain code that should always execute after the try block. Common exception handling keywords in Java include try, catch, throw, throws, and finally.

Uploaded by

Aditya B N
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)
31 views38 pages

Ooj Notes 8

The document provides an overview of exception handling in Java. It discusses that exceptions are objects that describe error conditions, and can be generated by the Java runtime system or manually in code. Code that could generate exceptions is placed in a try block, and exceptions can be caught using catch blocks. Finally blocks contain code that should always execute after the try block. Common exception handling keywords in Java include try, catch, throw, throws, and finally.

Uploaded by

Aditya B N
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/ 38

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.
Exceptions thrown by Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java
execution environment.
Manually generated exceptions are typically used to report some
error
1/4/2022condition to the caller of a method.
GRA 1
Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
Briefly, here is how they work.
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.
System-generated exceptions are automatically thrown by the
Java runtime 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.

1/4/2022 GRA 2
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
}
finally {
// block of code to be executed after try block ends
}

Here, ExceptionType is the type of exception that has occurred.


1/4/2022 GRA 3
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. This is also the
class that you will subclass to create your own custom exception types.
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. This chapter will not be dealing with
exceptions of type Error, because these are typically created in response to catastrophic
failures that cannot usually be handled by your program.

1/4/2022 GRA 4
1/4/2022 GRA 5
Exceptions and errors both are subclasses of Throwable class.
The error indicates a problem that mainly occurs due to the lack of
system resources and our application should not catch these types of
problems. Some of the examples of errors are system crash error and
out of memory error. Errors mostly occur at runtime that's they belong
to an unchecked type.
Exceptions are the problems which can occur at runtime and compile
time. It mainly occurs in the code written by the developers.
Exceptions are divided into two categories such as checked exceptions
and unchecked exceptions.

1/4/2022 GRA 6
difference between checked and unchecked
exceptions

checked exceptions are forced by compiler and used


to indicate exceptional conditions that are out of the
control of the program (for example, I/O errors),

unchecked exceptions are occurred during runtime


and used to indicate programming errors (for
example, a null pointer).

1/4/2022 GRA 7
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is
useful to see what happens when you don’t handle them. This small
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;
}
}
Here is the exception generated when this example is executed:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
1/4/2022 GRA 8
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
The resulting stack trace from the default exception handler
shows how the entire call stack is displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)

1/4/2022 GRA 9
Using try and catch

Although the default exception handler provided by the Java


run-time system is useful for debugging, you will usually want
to handle an exception yourself.
Doing so provides two benefits.

First, it allows you to fix the error.

Second, it prevents the program from automatically


terminating

1/4/2022 GRA 10
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.");
}
}
output:
Division by zero.
After catch statement.
1/4/2022 GRA 11
// Handle an exception and move on.
import java.util.Random;
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 (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
1/4/2022 GRA 12
}
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. For example, the catch block in the preceding program can be
rewritten like this:

catch (ArithmeticException e) {
System.out.println("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-by zero error displays the following message:

Exception: java.lang.ArithmeticException: / by zero

While it is of no particular value in this context, the ability to display a description


of an exception is valuable in other circumstances—particularly when you are
experimenting with exceptions or when you are debugging.
1/4/2022 GRA 13
Multiple catch Clauses
// Demonstrate multiple catch statements.
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("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
} 1/4/2022 GRA 14
Here is the output generated by running it both ways:

C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultipleCatches TestArg


a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

1/4/2022 GRA 15
/* 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.*/

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.");


}
}
}
1/4/2022 GRA 16
Nested try Statements
// An example of nested try statements.
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);

1/4/2022 GRA 17
try { // nested try block

/* If one command-line arg is used, then a divide-by-zero exception will be generated by the following
code. */
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 out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}/4/2022
1 GRA 18
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One


a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One Two


a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

1/4/2022 GRA 19
/* Try statements can be implicitly nested via calls to methods. */
class MethNestTry {
static void nesttry(int a) {
try { // nested try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */
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 out-of-bounds: " + e);
}
}

1/4/2022 GRA 20
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);
nesttry(a);
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

The output of this program is identical to that of the preceding


example

1/4/2022 GRA 21
Throw

So far, you have only been catching exceptions that are thrown by
the Java run-time system.
However, 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.

1/4/2022 GRA 22
// Demonstrate throw.
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);
} } }
output:
Caught inside demoproc.
1/4/2022 GRA 23
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.
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.

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
} 1/4/2022 GRA 24
// This program contains an error and will not compile.
class ThrowsDemo {

static void throwOne() {


System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

public static void main(String args[]) {


throwOne();
}
}

1/4/2022 GRA 25
// This is now correct.
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);
}
}
}
Output :
inside throwOne
caught java.lang.IllegalAccessException: demo
1/4/2022 GRA 26
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 exception-handling 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. This can be useful for closing file handles
and freeing up any other resources that might have been allocated at the
beginning of a method with the intent of disposing of them before returning. The
finally clause is optional. However, each try statement requires at least one catch
or a finally clause.
1/4/2022 GRA 27
// Demonstrate finally.
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
1/4/2022 GRA 28
}
// Execute a try block normally.
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();
}
}1/4/2022 GRA 29
output :

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally

1/4/2022 GRA 30
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.

As previously explained, 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 java.lang are listed

1/4/2022 GRA 31
1/4/2022 GRA 32
Table lists those exceptions defined by java.lang 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.

1/4/2022 GRA 33
Creating Your Own Exception Subclasses
Although Java’s built-in exceptions handle most common errors, you will
probably want to create your own exception types to handle situations
specific to your applications. This is quite easy to do: just define a
subclass of Exception (which is, of course, a subclass of Throwable). 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.

Exception defines four public constructors. Two support chained


exceptions, described in the next section. The other two are shown
here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second
1/4/2022
form lets you specify a description GRA
of the exception. 34
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
1/4/2022 GRA 35
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

1/4/2022 GRA 36
public class SumIsZeroException extends Exception
{
int s;
SumIsZeroException(int s)
{
this.s = s;

public String toString()


{ return "MyException "+s; //return "SUM IS ZERO
EXCEPTION";
}
}
1/4/2022 GRA 37
import java.util.Scanner;
public class Main {
public static void sum(int a, int b)throws SumIsZeroException
{ if(a+b==0) throw new SumIsZeroException(0);
else
if(a+b==99) throw new SumIsZeroException(99);
System.out.println("Sum = "+(a+b)); }

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("Enter first number : ");
int a = in.nextInt();
System.out.print("Enter second number : ");
int b = in.nextInt();
in.close();
try { sum(a, b); }
catch(SumIsZeroException e) { System.out.println(e); }
}}
1/4/2022 GRA 38

You might also like