Hey Guys, could you tell me the different ways to write throw method (Exception Handling) in a program.. I mean like we can write BufferedReader in many ways (2 ways so far i've studied)..

eg; 
1. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

2. BufferedReader br;
{
br = new BufferedReader(new InputStreamReader(System.in));
}

Recommended Answers

All 4 Replies

that is not related to Exception handling.
it's also not really different.

in the first statement, you initialize the BufferendReader the very moment you declare it.

in the second, you declare the BufferedReader, but instantiate it later.

this is not exception handling.

In the first example, you instantiate the BufferedReader the very instant you declare it.

In the second, you first declare it, but don't initialize it until later.

The3 Java Language Spec documents all this stuff definitively. For throw it says

14.18 The throw Statement
...
A throw statement causes an exception (§11) to be thrown
...
ThrowStatement: throw Expression ;
The Expression in a throw statement must denote either 1) a variable or value of
a reference type which is assignable (§5.2) to the type Throwable, ...

(plus a load of stuff about what happens if ot goes wrong)

So there's really not a lot to say in answer to your question. The only way to write it is "throw" followed by something that is or extends Throwable (eg an Exception).

You can do it in try block:

try { } catch (Exception e) { e.printStackTrace(); }

Or you can add on method throws IOException or what exception you need to catch...
You can write your own exceptions lik this:

class YourException extends Exception {
    YourException() {
        super("You can write your own message...!");
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.