Provide a description of the try .. catch statement. As part of your description you must describe how this statement can be used to handle errors and exceptions and include an example of try ... catch implemented to handle an error or exception within a Java program.
//EXAMPLE PROGRAM
// Exception Handling
// Simple try-catch block
class Demo
{
public static void main(String args[])
{
System.out.println("\n\t *** Program Start ***");
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c=a/b;
System.out.println("\n\t Division = "+ c);
}
catch(Exception e)
{
System.out.println("\n\t *** Exception caught ***");
System.out.println(e);
}
System.out.println("\n\t *** Program End ***");
}
}
OUTPUT :
[root@localhost ADON]# java Demo 8 4
*** Program Start ***
Division = 2
*** Program End ***
[root@localhost ADON]# java Demo 8 0
*** Program Start ***
*** Exception caught ***
java.lang.ArithmeticException: / by zero
*** Program End ***
[root@localhost ADON]# java Demo
*** Program Start ***
*** Exception caught ***
java.lang.ArrayIndexOutOfBoundsException: 0
*** Program End ***
[root@localhost ADON]#
Get Answers For Free
Most questions answered within 1 hours.