Program 1:
The syntax for Try and Catch block
try {
// write your code here
} catch (Exceptione) {
// catch block
}
Now, let’s learn about the program using try and catch block
class Test
{
public static void main(String[] args)
{
try
{
intnumber = 5 / 0;
System.out.println(“Try Block”);
}
catch (ArithmeticExceptionae)
Output is:ArithmeticException => / by zero
Program 2:
The syntax for Multiple Catch blocks
try
{
statement 1;
statement 2;
}
catch (Exception e)
{
System.out.println();
}
}
catch (Exception e)
{
System.out.println();
}
Now, let’s learn about Multiplecatchs block program
class List_Numbers
{
public int[] array_Numbers = new int[10];
public void writeList()
{
try
{
array_Numbers[9] = 10;
}
catch (NumberFormatException ne)
{
System.out.println(“NumberFormatException => ” + ne.getMessage());
}
catch (IndexOutOfBoundsExceptionie)
{
System.out.println(“IndexOutOfBoundsException => ” + ie.getMessage());
}
}
}
class Final {
public static void main(String[] args) {
List_Numbers list = new List_Numbers();
list.writeList();
}
}
Output
IndexOutOfBoundsException => Index 10 out of bounds for length 10
Program 3:
The syntax for Try, Catch and Finally block
try {
// write your code here
} catch (Exception e) {
// catch block
} finally {
// finally block
}
Now, let’s learn about Finally block
class Main {
public static void main(String[] args) {
try
{
intzero = 5 / 0;
}
catch (ArithmeticExceptionae)
{
System.out.println(“ArithmeticException => ” + ae.getMessage());
}
finally
{
System.out.println(“Finally block is always executed”);
}
}
}
Output:
ArithmeticException => / by zero
Finally block is always executed
Program 4:
The syntax for Multiple Tryblocks
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
Now, let’s learn about Multiple try block
class Exc
{
public static void main(String args[])
{
try{
try{
System.out.println(” divided arithmetic”);
int b =39/0;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
try{
inta[]=new int[4];
a[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println(“other statement);
}
catch(Exception e)
{
System.out.println(“Excetion handeled”);
}
System.out.println(“The normal flow”);
}
}
2 Responses