Unit08 - Exception Handing
Unit08 - Exception Handing
Instructor:
JAVA EXCEPTIONS
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't
use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether an
exception is handled or not.
EXCEPTION HANDLING
} finally {}
} catch(Exception_Class_Name ref){
} finally {}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10
Multi-catch block
A try block can be followed by one or more catch blocks.
Each catch block must contain a different exception handler.
You have to perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
Points to remember:
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
try {
int a[] = new int[5];
a[5] = 30 / 0;
System.out.println(a[10]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13
finally block
Java finally block is a block that is used to execute important
code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or
not.
Java finally block follows try or catch block.
Example:
Connection conn= null;
try {
conn= get the db conn;
//do some DML/DDL
} catch(SQLException ex) {
} finally {
conn.close();
}
Output:
java.lang.ArithmeticException: Not valid
at fa.training.utils.Validator.isAge(Validator.java:20)
at fa.training.jpe2.Main.main(Main.java:9)
Syntax:
Checked exception cannot be propagated using Checked exception can be propagated with throws.
throw only.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
int a=50/0;//ArithmeticException
String s = null;
System.out.println(s.length());//NullPointerException