Exceptions Exceptions: Lecture 09

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Exceptions Exceptions

Lecture09
What is an Exception? What is an Exception?
Exceptional event p
Error that occurs during runtime
Cause normal program flow to be disrupted
Examples
Divide by zero errors
Accessing the elements of an array beyond its range
Invalid input
Hard disk crash Hard disk crash
Opening a nonexistent file
Heap memory exhausted
Exceptions Exceptions
An exception in Java is an object that is created when an
abnormal situation arises in your program
This object has members that stores information about the This object has members that stores information about the
nature of the problem
An Exception is always an object of some subclass of the
standard class Throwable standard class Throwable
Java provides a very well defined hierarchy of Exceptions to deal
with situations which are unusual.
All Standard exceptions are covered by two direct subclasses of All Standard exceptions are covered by two direct subclasses of
the class Throwable
Class Error
Class Exception Class Exception
Classification of Exceptions

ClassNotFoundException
A ith ti E ti
IOException
Exception
ArithmeticException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Throwable Object
Many more classes
IllegalArgumentException
LinkageError
Error
VirtualMachineError
Many more classes
The Error and Exception Classes The Error and Exception Classes
Error class
Used by the Java runtime system to handle errors
occurring in the runtime environment
Generally beyond the control of user programs
Examples p
Out of memory errors
Hard disk crash
Exception class Exception class
Conditions that user programs can reasonably deal with
Usually the result of some flaws in the user program code
Examples Examples
Division by zero error
Array outofbounds error
Checked Exceptions vs. Unchecked
Exceptions Exceptions
and their subclasses Error , RuntimeException
are known as unchecked exceptions. All other p
exceptions are known as checked exceptions,
meaning that the compiler forces the g p
programmer to check and deal with the
exceptions. p
6
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example,
is thrown if you access an object NullPointerException a
through a reference variable before an object is assigned to it;
is thrown if you access an IndexOutOfBoundsException an
element in an array outside the bounds of the array.
Th th l i th t h ld b t d i th These are the logic errors that should be corrected in the
program.
Unchecked exceptions can occur anywhere in the program Unchecked exceptions can occur anywhere in the program.
To avoid cumbersome overuse of try-catch blocks, Java does
not mandate you to write code to catch unchecked exceptions
7
not mandate you to write code to catch unchecked exceptions.
Example Example
class DivByZero {
public static void main(String args[]) {
System.out.println(3/0);
System.out.println(Pls. print me.);
}}
Exception in thread "main java.lang.ArithmeticException: \ by zero at
DivByZero main(DivByZero java:3) DivByZero.main(DivByZero.java:3)
Default exception handler
Provided by Java runtime
P i t t ti d i ti Prints out exception description
Prints the stack trace
Causes the program to terminate
What Happens When an Exception
Occurs?
When an exception occurs within a method, the method p ,
creates an exception object and hands it off to the runtime
system
Creating an exception object and handing it to the runtime systemis Creating an exception object and handing it to the runtime system is
called throwing an exception
Exception object contains information about the error, including its
type and the state of the programwhen the error occurred type and the state of the program when the error occurred
Dealing With Exceptions Dealing With Exceptions
For all subclasses of Exception Class(except
RuntimeException) you must include code to deal with p ) y
them
If your program has the potential to generate an exception
of such a type, you have got two choices
Handle the exception within the method
Register that your method may throw such an exception (You
are passing the exception on)
If d i h d il If you do neither your code wont compile
Catching Exceptions:
h h The trycatch Statements
Syntax:
try {
<code to be monitored for exceptions>
}
catch (<ExceptionType1> <ObjName>) {
h dl if E i T 1 <handler if ExceptionType1 occurs>
}
catch (<ExceptionTypeN> <ObjName>) { catch (<ExceptionTypeN> <ObjName>) {
<handler if ExceptionTypeN occurs>
}}
Example1 Example 1
class DivByZero {
public static void main(String args[]) {
try {
System.out.println(3/0);
System.out.println(Please print me.);
}
catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}}
System.out.println(After exception.);
}
Example2 Example 2
class MultipleCatch {
public static void main(String args[]) {
{ try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
}}
catch (ArithmeticException exc) {
System.out.println(Divisor was 0.);
}}
catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(Missing argument.);
}}
System.out.println(After exception.);
}
}
Nested Try
class NestedTryDemo {
public static void main(String args[]){
try { y {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]); g p ( g [ ]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println(Div by zero error!"); System.out.println( Div by zero error! );
}
}
catch (ArrayIndexOutOfBoundsException) { catch (ArrayIndexOutOfBoundsException) {
System.out.println(Need 2 parameters!");
}
}} }}
Nested trys with methods Nested try s with methods
class NestedTryDemo2 {
static void nestedTry(String args[]) {
try { try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b); y p ( )
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
}}
public static void main(String args[]){
try {
t dT ( ) nestedTry(args);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Need 2 parameters!");
}}
}}
finally finally
try {
<code to be monitored for exceptions> <code to be monitored for exceptions>
}
catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>
}
finally {
<code to be executed before the try block ends>
}}
Finally keyword Finally keyword
Block of code is always executed despite of Block of code is always executed despite of
different scenarios:
Forced exit occurs using a return, a continue or a g ,
break statement
Normal completion
Caught exception thrown
Exception was thrown and caught in the method
U ht ti th Uncaught exception thrown
Exception thrown was not specified in any catch block
in the method
Example
l Fi ll D { public static void main(String args[]){ class FinallyDemo {
static void myMethod(int n) throws Exception{
try {
switch(n) {
public static void main(String args[]){
for (int i=1; i<=4; i++) {
try {
FinallyDemo myMethod(i);
switch(n) {
case 1: System.out.println("1st case");
return;
case 3: System.out.println("3rd case");
FinallyDemo.myMethod(i);
}
catch (Exception e){
throw new RuntimeException("3!");
case 4: System.out.println("4th case");
throw new Exception("4!");
2 S t t i tl ("2 d ")
System.out.print("Exception
caught: ");
System.out.println(e.getMessage(
)); case 2: System.out.println("2nd case");
}
} catch (RuntimeException e) {
System.out.print("RuntimeException: ");
));
}
System.out.println();
}
System.out.print( RuntimeException: );
System.out.println(e.getMessage());
}
finally{System.out.println("in finally try blk entered");}
}
}
}
System.out.println("after finally");
}
Example Example
public static void main(String args[]){
for (int i=1; i<=4; i++) { for (int i=1; i<=4; i++) {
try {
FinallyDemo.myMethod(i);
}}
catch (Exception e){
System.out.print("Exception caught: "); System.out.print( Exception caught: );
System.out.println(e.getMessage());
}
S t t i tl () System.out.println();
}
}
output
1st case
in finally try blk entered
2nd case
in finally try blk entered
after finally after finally
3rd case
RuntimeException: case 3! p
in finally try blk entered
after finally
4th case
in finally try blk entered
Exception caught: 4!

You might also like