Professional Documents
Culture Documents
CSC-210
Object-Oriented Programming
Lecturer
Sameena Javaid
https://sites.google.com/site/sameenajavaidcs
EXCEPTIONS
A Little Demo
public class Test {
public static void main(String[] args) {
int i = 6;
int j = 3;
System.out.println(i/j);
}
}
Output :
2
A Little Demo
public class Test {
public static void main(String[] args) {
int i = 6;
int j = 0;
System.out.println(i/j);
}
}
Output :
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4)
Exception Classes
Object
2
Error Runtime
Exceptions
catch(Exception_Class reference)
{
//Catch the exception and displays that
exception
}
Multiple Catches
Try {
• When there is a //statements
chance of getting }
different types of
catch(Exception_Class reference) {
exceptions we use //statements for one type of
multiple catch block exception
for a try block. }
catch(Exception_Class reference) {
//statements for other type of
exception
}
class Multiple_Catch {
Multiple-Catch Example
catch(ArrayIndexOutOfBoundsException
arrayexception)
int n; {
int array[]=new int[3]; System.out.println(arrayexception);
Multiple_Catch(int n) }
{
try{ catch(ArithmeticException divideexception)
if(n==0) {
System.out.println(divideexception);
System.out.println(5/n);
}
else{
}
array[3]=n;
}//class end
System.out.println(array);
}
}
© Bahria University Department of Computer Science | Bahria University 12
Discovering Knowledge
}
}
try{
throw new Exception_class(“message”);
}
catch(Exception_class reference){
//statements
}
Types of Exception
• Run-time Exceptions.
• Compile Enforced Exception
Run-Time Exceptions
• Are also called as Unchecked Exception.
• These exceptions are handled at run-time i.e by JVM
after they have occurred by using try and catch
block.
• Eg: ArrayIndexOutOfBoundsException,
ArithmeticException
NullPointerException
Complier-enforced Exceptions
• Are also called as Checked Exceptions.
• These exceptions are handled by java complier
before they occur by using throws keyword.
• Eg: IOException,
FileNotFoundException
User-defined Exceptions
• Across built-in exceptions user can also
define his own exceptions.
• It can be done by defining a class that extends
Exception class and creating a constructor of
the class (user-defined) with string argument
to print that message when exception occurs.
User-defined Exceptions
Advantages of Exception
• The program will still execute even if an
exception arises i.e finally block.
• If you can't handle the exception JVM will
handle the exception if we use throws
keyword.
• We can differentiate the exceptions that have
occurred.