Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   How to throw Exceptions in Java? (http://www.go4expert.com/articles/throw-exceptions-java-t4149/)

Sanskruti 5May2007 17:50

How to throw Exceptions in Java?
 
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 runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

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.

The throw Statement



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.

Code: Java

throw someThrowableObject;

If you want to throw an exception explicitly then you need to use the throw clause. All the system-defined exceptions are thrown automatically, but the user-defined exceptions must be thrown explicitly using the throw clause. It takes the form as:

Code: Java

try
{

    // statements
    throw new UserDefinedException( );
    // statements
}catch (UserDefinedException e)
{
    System.out.printIn (“User defined exception caught”);
}

The UserDefinedException is a class made specifically to handle an exception and it is encapsulating some specific kind of user defined behaviour. This exception is raised explicitly using the throw clause. At the same time the catch clause is there ready to catch the same exception object.

Consider the following example in which a system defined exception is deliberately thrown in order to demonstrate the functionality of the throw clause:

Code: Java

class Throw_clause
{
    public static void main (String args [ ])
    {
        try
        {
            throw new NullPointerException ( );
        } catch (NullPointerException e)
        {
            System.out.println ("Invalid reference use");
        }
    }
}

Output:

Code:

Invalid reference use
In the above example the throw clause throws an object of a system defined exception NullPointerException, which is actually thrown when an object storing a null pointer is reference. Thus, as soon as an the exception is raised it is caught with the catch clause, the statement inside the catch clause are executed and we get the above output.



All times are GMT +5.5. The time now is 15:27.