Java exception handling using throw

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java run time environment. Regardless of what throws the exception, it's always thrown with the throw statement.

As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.


All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

throw someThrowableObject;

Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.

class throwdemo
    {
     static void demo()
        {
          try
             {
throw new NullPointerException("Demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside Demo");
throw e;
}
}
public static void main(String arg[])
{
try
{
demo();
}
catch(NullPointerException e)
{

System.out.println("Recaught :"+e);
}
}
}


This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then re thrown.

Output

Caught inside demo.
Recaught: java.lang.NullPointerException: demo


Java exception handling using throw


The program also illustrates how to create one of Java's standard exception objects. Pay close attention to this line:

throw new NullPointerException("demo");

Here, new is used to construct an instance of NullPointerException. All of Java's built-in run-time exceptions have two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org