Home » Posts tagged 'exception'

Tag Archives: exception

Finally Keyword in Java

In java exception handling, any code that we want to must be execute put inside the finally block.

After the execution of try and catch block, finally block executes. try block must be used with either catch or finally, or with both.

Normally when exception occurs then further programs never executes. 

But either exception occurs or not, in both condition finally block executes.

Example1:  write a program to demonstrate the use of finally block with only try.

In the above program, we use two conditions, in the first condition we set array a is “a[100] = 20;”

 than exception occurs the following two lines will never execute

System.out.println(“Never Execute”);

System.out.println(“After try/finally “);

But finally block executes. And output is:

In the second condition, we set array a is “a[5] = 10;”  than there is no exception occurs.

use finally block executes. The output is:

Note: In this program, we have not used catch block, means when an exception will be generated then the program will never execute but finally must be executed .

Example2: write a program to demonstrate the use of finally block with try catch.

In the above program, we uses two condition, in the first condition we set array a is “a[100] = 20;”  than exception occurs the following  line will not execute

            System.out.println(“Never Execute”);

and exception is thrown which is caught bycatch(ArrayIndexOutOfBoundException  e)” after the catch rest of the program will execute. and the output is:

Java Throws Keyword

In a java programming, throws keyword list the type of exception that a method might throw.

In the throws clause, we declare all the exception that a method can throw.

  Syntax:         

                                               

Here, exception1, exception2 are comma, list of the exception that a method can throw.

Example:

Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Throw Keyword in Java

In java programming, If the exception occurs within try block it is thrown.

A system generate exception is automatically thrown by java run time system but if we want to  manually thrown an exception, we can do so by using throw keyword. 

Syntax: 

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example: write a program to demonstrate throw keyword.

Note:  In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

            

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.

Types of Exceptions

In java programming, Exception class is a subclass of class Throwable.

Apart from Exception class, class Error is also derived from class Throwable.

Error: In java programming, error is Unrecoverable. It occurs during compile time.

For example, if we write wrong syntax then error will generate during compile time.

There are two types of Exception

  1. Checked Exception
  2. Unchecked Exception

Checked Exception

Here is the list of some checked exception

  1. IllegalAccessException: in java programming, this exception occurs when access to a class is denied.
  2. ClassNotFoundException: this exception occurs when class not found.
  3. NoSuchMethodException : when a requested method dose not exist this exception occurs.
  4. CloneNotSupportedException: in java programming,If you are trying to use the clone method in a classwhere Cloneable interface is not implemented, it throwsCloneNotSupportedException. Clone() method is used to create exactcopy of a object
  5. InterruptedException : in java, when we work with multiple threads then one thread  interrupts another thread.  
Exception Hierarchy

Unchecked Exception

  1. ArithmeticException : in java programming this exception, represent the arithmetic error, such as divided-by-zero.
  2. IndexOutOfBoundsException: when some type of index is out of bounds this exception occur.
    • ArrayIndexOutOfBoundsException: in java programming this exception represent the Array index is out of bound. This condition is arises when we try to access illegal array index.
    • StringIndexOutOfBoundsException : in java programming, when we access the index outside the bound of string than this exception occurs.
  3. NegativeArraySizeException: when array is created with negative size than this exception is arises.
  4. NullPointerException: in java programming this exception occurs when invalid use of null reference.
  5. IllegalThreadStateException: this exception occurs , when required operation not compatible with current thread state.
Managed by MochaHost - Fast & Easy WordPress Hosting