Unit 6 - PNR - Part 1
Unit 6 - PNR - Part 1
Exception Handling
// array of size 4.
int[] arr = new int[4];
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
int a=50/0;
String s=null;
S.O.P(s.length());
For E.g
String s="abc";
int i=Integer.parseInt(s);
Eg:
int a[]=new int[4];
a[10]=50
2. Unchecked Exceptions
– are exceptions derived from Error and RuntimeException classes
– are usually irrecoverable and not handled explicitly
– are not checked by the compiler but they are checked at runtime.
– e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
Error is irrecoverable
2 CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3 IllegalAccessException
Access to a class is denied.
4 InstantiationException
Attempt to create an object of an abstract class or interface.
5 InterruptedException
One thread has been interrupted by another thread.
6 NoSuchFieldException
A requested field does not exist.
7 NoSuchMethodException
A requested method does not exist
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible type.
4 ClassCastException
Invalid cast.
5 IllegalArgumentException
Illegal argument used to invoke a method.
6 IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
System.out.println("normal flow...");
}
}
Dr. Purvi Ramanuj
Output:exception handled
normal flow...
System.out.println("normal flow...");
}
}
System.out.println("normal flow...");
}
}
System.out.println("normal flow...");
}
}
Dr. Purvi Ramanuj
• Output:exception handled
• normal flow...
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Dr. Purvi Ramanuj
Starting of try block
Catch Block
MyException Occurred: This is My error
Message
}
}
class pb6 {
public static void main(String args[]) {
int p=0,q=0,r=0;
try{
for(int i=0;i<args.length;i++) {
if(Integer.parseInt(args[i])>=40) {
p++;
}
else if(Integer.parseInt(args[i])<0) {
q++;
throw new IllegalMarkException();
}
}
}
catch(IllegalMarkException j) {
System.out.println("Illegal Mark");
}