Lecture 12 Exception Handling With Assertion
Lecture 12 Exception Handling With Assertion
Exception Handling
Contact Info:
Room No: BS-04, CED
1 Email: [email protected]
Course Books
Text Book:
Herbert Schildt, Java: The Complete Reference, 12th
Edition ,McGraw-Hill Education.
Deitel, Paul, Java How to Program, 11th Edition, Pearson,
2017
Reference Books:
Horton, Ivor, Beginning Java, 7th Edition, Wrox, 2011
2
Course Instructors
20
30
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Exception Classes
8
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
Exception ClassNotFoundException
describes errors
caused by your IOException
program and ArithmeticException
external Exception AWTException
circumstances. NullPointerException
These errors can RuntimeException
be caught and IndexOutOfBoundsException
handled
Object by your
Throwable Several more classes
IllegalArgumentException
program.
LinkageError Several more classes
VirtualMachineError
Error
AWTError
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
RuntimeException is
Error
caused by programming
AWTError errors, such as bad
casting, accessing an
Several more classes out-of-bounds array, and
numeric errors.
12 Without Error Handling –
Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
No compilation errors. While running it reports an error and stops w
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java
Traditional way of Error
13
Handling - Example 2
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
else{
Program reaches here
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
14 Error Handling
Any program can find itself in unusual circumstances – Error
Conditions.
try Block
Throws
exception
catch Block
Object
Statements that
handle the exception
22
Syntax of Exception
Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
With Exception Handling
23
- Example 3
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
Program Reaches here
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Finding a Sum of Integer
Values Passed as
24
Division(2,2)
i/j 1
return from division
finally
Return from main
36
Catching and
Propagating Exceptions
Exceptions raised in try block can be caught
and then they can be thrown again/propagated
after performing some operations. This can be
done by using the keyword “throw” as follows:
throw exception-object;
OR
throw new Throwable_Subclass;
Catching and Propagating
37
Exceptions
If an exception is raise in try but not catch than it goes to
finally but if finally also throw some other exception then
the rest of code is not execute and the last abrupt exception
is throw by default handler.
catch (ArthematicException e){
s.o.p(“except caught”);
}
throw e;
}
//goes to default handler as we run in sequence.
Exception that are from run time Exception; and error are
uncaught exception.
All other from exception class are caughtable.
With Exception Handling
38
- Example 7
class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program Does Not
reach here
catch(ArithmeticException e){
when exception occurs System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
With Exception Handling
- Example 8
39
class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program catch(ArithmeticException e){
reaches here System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
Using printStackTrace and
getMessage
Class Throwable
Superclass of all exceptions
Offers method printStackTrace
Prints method call stack for caught
Exception object
Most recent method on top of stack
Helpful for testing/debugging
Constructors
Exception()
Exception( String informationString )
informationString may be accessed
with method getMessage
With Exception Handling
41 - Example 9 Call method1, which calls
class WithExceptionCatchThrows{ method2, which calls method3,
which throws an exception.
public static void main(String[] args){
try{
method1();
} getMessage prints the
catch(Exception e){ String the Exception was
System.err.println( e.getMessage() + "\n" ); initialized with.
e.printStackTrace();
printStackTrace prints the
} methods in this order:
} method3
public static void method1() throws Exception{ method2
method2(); method1
main
} (order they were called when
public static void method2() throws Exception{ exception occurred)
method3();}
public static void method3() throws Exception{
throw new Exception( "Exception thrown in method3" );
}}
42 With Exception Handling -
Example 9 output
Problem Statement :
Consider the example of the Circle
class
Circle class had the following
constructor
public Circle(double centreX, double centreY,
double radius){
x = centreX; y = centreY; r = radius;
}
private double r;
class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
e.printError();
}
}
}
Example 2: Defining your
54
own exceptions
public class DivException extends Exception {
DivException()
{super(“Div error Exception…");} Exception have two constructors
String argument
Zero argument
DivException(String str)
{super(str);}
User will throw this exception if divisor is 0
@override
public String getMessage(){
return super.getMessage();
}
}
Example 2: Defining
55
MyException(String str)
User will throw this exception if dividend <divisor
{super(str);} A=5
B=10
A<B
@Override
public String getMessage(){
return super.getMessage();
}
}
Throwing & Catching the
56 exception
public class testMyException { finally{
public static void main(String[] System.out.println("Close
args){
File");
int a=10,b=20;
System.out.println("pakistan");
try{
}
if(a<b) throw new MyException(); System.out.println("hello
divide(a,b);
Karachi");
} }
catch(MyException e ){ static void divide(int i,int j) throws
System.out.println("MyException DivException{
Comes"); if(j==0) throw new
System.out.println(""+e.toString()); DivException();
} catch(DivException e ){
System.out.println(""+i/j);
System.out.println("DivException
Comes");
System.out.println(""+e.toString());
}
}
}
Example 2: output
57
If a=10 b=20
pakistan
MyException COmes
exception.MyException: a<b in my Exception…
Close File
hello Karachi
If a=20 b=0
pakistan
DivException COmes
exception.DivException
Close File
hello Karachi
Exceptions are ubiquitous in Java
class AssertionExample{
public static void main( String args[] ){
System.out.println("value is "+value);
}
}
Run Assertion
64