View RSS Feed

My Java Tips

Exception Handling In Java

Rate this Entry
by , 11-08-2011 at 05:58 PM (834 Views)
Exception handling is an integral part of programming. In Java exceptions are itself defined as objects in other words throwing an exception is throwing an object. “ Throwable ”, declared in “java.lang package” is the parent class for all the classes that a program can instantiate and throw.


Basically Throwable has two direct subclasses.

Exception.
Error.

Exceptions (means members of the Exception family) are thrown to indicate abnormal conditions that can often be handled by some catcher, Though there is a possibility that they may not be caught and therefore result may be a dead thread.

Errors (members of the Error family) are usually thrown for more serious problems like OutOfMemoryError. That may not be easy to handle in programs so Errors are usually thrown by the methods of the Java API, or by the JVM itself. So in general, the code you write should throw only exceptions, not errors. Errors cannot be caught.

The keywords reserved for the exception handling part in Java is listed below.

try: Used along with catch or finally keyword so the code contained in try block can be handled for exceptions in catch block.
catch: usually receives an exception from the code present in try block.
throw: To throw object of Exception class family.
throws : Used along with a method to declare which type of exceptions are thrown by this method.

Exceptions thrown by “ throws ” clause can further be handled in “ try-catch ” block of the caller method.
RunTimeException is not mandatory to be thrown, As Java API itself throws such exceptions in many situations like arithmetic errors, illegal argument passed to method etc.
As per the business needs programmers can declare their own exceptions which are inherited from Exception class

Here is a sample program for exception handling.
Java Code:
public class CalculationException extends Exception {

public CalculationException(String msg){

 	super(msg);

 }

}

public class ExceptionTest {

int divide(int num,int div) throws CalculationException{

 	if(div==0)

 		throw new CalculationException("can not divide by zero");

return num/div;

 }

 public static void main(String[] args) {

 	ExceptionTest test = new ExceptionTest();

 	try {

 		System.out.println(test.divide(2,0));

 	} catch (CalculationException e) {

 		e.printStackTrace();

 	}

 }

}

Submit "Exception Handling In Java" to Facebook Submit "Exception Handling In Java" to Digg Submit "Exception Handling In Java" to del.icio.us Submit "Exception Handling In Java" to StumbleUpon Submit "Exception Handling In Java" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments