Ooj Notes 8
Ooj Notes 8
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
}
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
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
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
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:
C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
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
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
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);
}
}
}
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
} }
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
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.
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;