Exceptions and Exception handling

Exceptions and Exception handling


Posted in : Core Java Posted on : October 9, 2010 at 6:42 PM Comments : [ 0 ]

This section contains the detail about the Exceptions and Exception handling in java.

Exceptions and Exception handling

In java , exception is an object that describe an erroneous condition that has occurred in as piece of code. Java exception handling is managed through five keywords : try, catch , throw, throws and finally.

Java's built-in Exceptions

Two categories of Java's built in exception are :

1. Unchecked exception

2. Checked exception

Unchecked Exception : Since 'java.lang' is implicitly imported into all Java programs, most exceptions derived from 'RuntimeException' are automatically available. Also, they need not be included in any method's 'throws' list. These are called 'Unchecked Exception'. Some example of these kind are : ArithmeticException, NullPointerException, ClassCastException etc.

Checked Exception : Checked Exceptions are those exceptions defined by 'java.lang' that must be included in a method's 'throws' list if that method can generate one of the given below exceptions and does not handle it itself.

Complete List of Checked Exceptions :

  • ClassNotFoundException
  • CloneNotSupportException
  • IllegalAccessException
  • InstantiationException
  • InterruptedException
  • NoSuchFieldException
  • NoSuchMethodException

try and catch

In try block, we put the code which you want to monitor for exception. You can handle the exception thrown by the code using catch block. To throw exception manually, use keyword throw. Any exception that is thrown out of a method must be specified as such by throws clause. The code which must be executed, before a method returns value, should be placed in finally block .

Example :


public class TryCatch {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed" + a);
} catch (ArithmeticException e) {
System.out.println("Divided by zero");
}
System.out.println("After catch statement");
}
}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac TryCatch .java

C:\Program Files\Java\jdk1.6.0_18\bin>java TryCatch
Divided by zero
After catch statement

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics