Sunday 5 August 2012

How to Throw Exceptions in Java

It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:


throw ThrowableInstance;


Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions.There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.


The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.


Here is a sample program that creates and throws an exception. 



class MyException extends Exception {

 public MyException(String msg) {
  super(msg);
 }
}

public class Test {

 static int divide(int first, int second) throws MyException {
  if (second == 0)
   throw new MyException("can't be divided by zero");
  return first / second;
 }

 public static void main(String[] args) {
  try {
   System.out.println(divide(4, 0));
  } catch (MyException exc) {
   exc.printStackTrace();
  }
 }
}


The output is:


MyException: can't be divided by zero
at Test.divide(Test.java:12)
at Test.main(Test.java:18)

No comments:

Post a Comment