Home » java » try catch blocks in Java

try catch blocks in Java

Que. Write a program to create a arithmetic exception and handle whit try catch block.

Output

Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of exception “ArithmeticException”.

When we print the value of “e “ it will print  ( java.lang.ArithmeticException:/by zero                                                                    at  Test.main(Test.java:6) )

  • ArithmeticException is an exception class which resides in java.lang package.
  • “/by zero”  is a type of arithmetic exception (divided by zero).
  • “Test” is the name of the class.
  • “main” is a method in which an exception occurs.
  • 6 is line number in which exception occured.

Multiple catch Clause

In java programming, when within a try block multiple exception occurs than for handling those multiple exception we use multiple catch with single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

Unreachable Code:

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example : Write a program to demonstrate unreachable code.

Note: If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of Exception class . 

     Then the first catch statement will handle all exception based error, including Arithmetic Exception therefore second catch statement will never execute.

 To solve the problem, reverse the order of catch statement.  

Nested try statement

In java programming, it is possible to create a try block within another try block. Such try block is known as nested try.

Example:

If there is no command line argument present then the output.

If there is no command line argument present then the output.

Managed by MochaHost - Fast & Easy WordPress Hosting