EXCEPTION FUNDAMENTALS
try { } catch (Exception_Class referenceobject) { }
Syntax of try with finally
try { } finally{ }
syntax of try with catch and finally both
try{ }catch(Exception_Class referenceobject){ } finally{}
You can use multiple catch block with single try block.
Syntax of try with multiple catch
try{ } catch(Exception_Class_Type1 referenceobject1){} catch(Exception_Class_Type2 referenceobject2){} catch(Exception_Class_Type3 referenceobject3){}
In multiple catch block if you have to run same code on each catch block so either you have to duplicate same code in each block or use finally block.
Using finally is not good because this block of code will run in respective of exception thrown or not. So lot of duplicate code will come which sometime makes code complex to read. So Java came with enhanced version of writing of multiple catch block in JDK7
syntax of multiple catch block in JDK7
try{ } catch(Exception_Class_Type1 | Exception_Class_Type2 | Exception_Class_Type3 referenceobject){ referecenobject.printStackTrace(); }
Example of try and catch block
1
2
3
4
5
6
|
public class ExceptionTest {
public static void main(String args[]) {
int a = 4 / 0;
System.out.println("after exception...");
}
}
|
O/P:
But if programmer handles the exception, rest of the code will be also executed.
Let's see below Program
1
2
3
4
5
6
7
8
9
10
11
|
public class ExceptionTest {
public static void main(String args[]) {
try {
int a = 4 / 0;
}
catch (ArithmeticException airthmaticexception) {
System.out.println(airthmaticexception);
}
System.out.println("after exception...");
}
}
|
O/P: