Upload
sarge-chisanga
View
227
Download
0
Embed Size (px)
Citation preview
8/11/2019 Lecture 09 Exceptions
1/20
Lecture09
8/11/2019 Lecture 09 Exceptions
2/20
Exce tional event
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
Opening a nonexistent file
Heap memory exhausted
8/11/2019 Lecture 09 Exceptions
3/20
An exception in Java is an object that is created when anabnormal situation arises in your program
nature of the problem
An Exception is always an object of some subclass of the
Java provides a very well defined hierarchy of Exceptions to deal
with situations which are unusual.
the class Throwable
Class Error
8/11/2019 Lecture 09 Exceptions
4/20
Classification of Exceptions
ClassNotFoundException
IOException
Exception
r me c xcep on
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
ThrowableObject
Many more classes
IllegalArgumentException
LinkageError
Error VirtualMachineError
Many more classes
8/11/2019 Lecture 09 Exceptions
5/20
Error class
Used by the Java runtime system to handle errorsoccurring in the runtime environment
Generally beyond the control of user programs Exam les
Out of memory errors
Hard disk crash
Exce tion class Conditions that user programs can reasonably deal with
Usually the result of some flaws in the user program code
Division by zero error
Array outofbounds error
8/11/2019 Lecture 09 Exceptions
6/20
Checked Exceptions vs. Unchecked
and their subclassesError,RuntimeExceptionare known as unchecked exce tions. All other
exceptions are known as checked exceptions,
meanin that the com iler forces theprogrammer to check and deal with the
exce tions.
6
8/11/2019 Lecture 09 Exceptions
7/20
Unchecked Exceptions
In most cases, unchecked exceptions reflect programminglogic errors that are not recoverable. For example,
is thrown if you access an objectNullPointerExceptiona
through a reference variable before an object is assigned to it;
is thrown if you access anIndexOutOfBoundsExceptionan
element in an array outside the bounds of the array.
ese are e og c errors a s ou e correc e n e
program.
.
To avoid cumbersome overuse of try-catch blocks, Java does
7
.
8/11/2019 Lecture 09 Exceptions
8/20
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. .
Default exception handler
Provided by Java runtime
r n s ou excep on escr p on
Prints the stack trace
Causes the program to terminate
8/11/2019 Lecture 09 Exceptions
9/20
What Happens When an Exception
Occurs? When an exce tion occurs within a method the method
creates an exception object and hands it off to the runtime
system
called throwing an exception
Exception object contains information about the error, including its
8/11/2019 Lecture 09 Exceptions
10/20
For all subclasses of Exception Class(except
RuntimeExce tion ou must include code to deal with
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)
I you o ne t er your co e won t comp e
8/11/2019 Lecture 09 Exceptions
11/20
Catching Exceptions:
The trycatch Statements
Syntax:
try {
}
catch ( ) {< an er xcept on ype occurs>
}
8/11/2019 Lecture 09 Exceptions
12/20
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.);
}
8/11/2019 Lecture 09 Exceptions
13/20
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.);
}
}
8/11/2019 Lecture 09 Exceptions
14/20
Nested Try
class NestedTryDemo {public static void main(String args[]){
tr {
int a = Integer.parseInt(args[0]);
try {int b = Inte er. arseInt ar s 1
System.out.println(a/b);
} catch (ArithmeticException e) {S stem.out. rintln Div b zero error!"
}
}
System.out.println(Need 2 parameters!");
}
8/11/2019 Lecture 09 Exceptions
15/20
class NestedTryDemo2 {
static void nestedTry(String args[]) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
}}
public static void main(String args[]){
try {
nes e ry args ;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Need 2 parameters!");
}}
8/11/2019 Lecture 09 Exceptions
16/20
try {
}catch ( ) {
}finally {
8/11/2019 Lecture 09 Exceptions
17/20
different scenarios: Forced exit occurs usin a return a continue or a
break statement
Normal completion Caught exception thrown
Exception was thrown and caught in the method
ncaug excep on rown Exception thrown was not specified in any catch block
in the method
8/11/2019 Lecture 09 Exceptions
18/20
Examplec ass na y emo
static void myMethod(int n) throws Exception{
try {
for (int i=1; i
8/11/2019 Lecture 09 Exceptions
19/20
public static void main(String args[]){
= =
try { FinallyDemo.myMethod(i);
}
catch (Exception e){
S stem.out. rint "Exce tion cau ht: "
System.out.println(e.getMessage());
}
ys em.ou .pr n n ;
}
}
8/11/2019 Lecture 09 Exceptions
20/20
output
1st case
in finally try blk entered
2nd case
in finally try blk entered
3rd case
RuntimeException: case 3!
in finally try blk entered
after finally
4th case
in finally try blk entered
Exception caught: 4!