SE101 Lec6 ExceptionHandling
SE101 Lec6 ExceptionHandling
Exception Handling
Exception:
1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
3) Error
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
This means that code that might throw certain exceptions must be enclosed
by either of the following:
A try/catch block is placed around the code that might generate an exception.
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
Multiple Catch Blocks:
A try block can be followed by multiple catch blocks.
try{
// protected code
}
catch (ExceptionName1 e1){
}
e1
catch (ExceptionName2 e2){
}
e2
catch (ExceptionName3 e3){
} e3
finally clause:
finally {
// this block always executes
}
The finally keyword is used to create a block of code that follows a try
block.
Note:
try{
System.out.println("Accessing element three :" + a[3]);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
Answer:
try {
} finally {
}
Question: What exception types can be caught by
the following handler?
catch (Exception e) {
}
Question: Is there anything wrong with this exception
handler as written? Will this code compile?
try {
} catch (Exception e) {
} catch (ArithmeticException a) {
}
Question: Match each situation in the first list with an item in the second list.
a.
int[] A;
A[0] = 0;
b.
The JVM starts running your program, but the JVM can't find the Java platform
classes. (The Java platform classes reside in classes.zip or rt.jar.)
c.
A program is reading a stream and reaches the end of stream marker.
d.
Before closing the stream and after reaching the end of stream marker, a program
tries to read the stream again.
__error
__checked exception
__compile error
__no exception
Thank You