Java : Exceptions (try catch)
1. Creating and Catching an Exception
public void crossFingers()
(
try{
Object.takeRisk();
) catch (BadException ex) // "ex" can be any variable
System. out.println ("Aaarqh! ") ;
ex .printStackTrace () ;
}
}
public void takeRisk () throws BadException {
if (abandonAllHope) {
throw new BadException();
}
}
---------------------
2. A finally block - runs regardless of an exception or even if the catch has a return statement
try (
turnOvenOn();
x.bake () ;
}catch (BakingException ex)
ex.printStackTrace();
}finally { //runs regardless of an exception or even if the catch has a return statement
turnOvenOff();
}
3. Multiple try catch
try {
throw new IOException();
}catch (FileNotFoundException f){
}catch (IOException e){
System.out.println(e); //output : java.lang.NullPointerException
e.printStackTrace; //output : java.io.IOException at package.Test.main(Test.java:74)
}catch (Exception e){ //Catches all sorts of Exception should be placed LAST
//If passed 1st any catch block belowing will be skipped
}finally{
}
4. Multiple catch Using OR (|)
try {
do something ;
}catch (FileNotFoundException | IOException e){ //Catch executes when either of the 2 exception occur
}
5. What you can do inside catch block ?
- e.printStackTrace()
- e.getmessage();
- log.error("Ops!", e); //Using logging framework like logback or log4j
- "USER CAN DO ANY OPERATIONS"
6. What is Throwable t ?
- In normal cases we should always catch sub-classes of Exception.
Example :
try {
do something ;
catch(throwable t){ //"throwable" is super class of exception
}
Congratulations guys, quality information you have given!!!..Its really useful blog. Thanks for sharing this useful information..java training in chennai | chennai's no.1 java training in chennai | best java institute in chennai
ReplyDeleteNice tutorial for Java try-catch block
ReplyDeletethanks for this post.
Thank you !! Very usefull !!
ReplyDeletedot net training in chennai
matlab training in chennai
embedded system training in chennai