Java catch multiple exceptions
Java catch multiple exceptions
o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Case 3
Let's see the java finally example where exception occurs and handled.
1. throw exception;
Output:
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
Output:exception handled
normal flow...
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:Runtime Exception
Difference between throw and throws
Click me for details
1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2) Checked exception cannot be propagated using Checked exception can be propagated with throws.
throw only.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to
method and variable. Final class can't be important code, it will be perform clean up
inherited, final method can't be overridden executed whether processing just before
and final variable value can't be changed. exception is handled or object is garbage
not. collected.