Sunday, March 13, 2011

Throwing the Exceptions from a method in java

We saw the code here which has to deal with the exception. Then we saw how to handle exceptions like these, here.
But sometimes, it's appropriate for your code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception.
For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all of the users of your package. In this case, it's better to not catch the exception and to allow someone further up the call stack to handle it.

If the writeList method doesn't catch the exceptions that can occur within it, then the writeList method must specify that it can throw them. Let's modify the writeList method to specify the methods that it can throw. To remind you, here's the original version of thewriteList method:
public void writeList() {
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = "
+ victor.elementAt(i));}

So we have 2 exceptions.

As you recall, the new FileWriter("OutFile.txt") statement might throw an IOException (which is not a runtime exception). The victor.elementAt(i)statement can throw an ArrayIndexOutofBoundsException (which, as a subclass of RuntimeException, is a runtime exception).

 

Syntax for throws


To specify that writeList throws these two exceptions, you add a throws clause to the method signature for the writeList method. The throws clause is composed of the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The throws clause goes after the method name and argument list and before the curly bracket that defines the scope of the method. Here's an example:


public void writeList throws IOException,
ArrayIndexOutOfBoundsException {

Note:

Remember that ArrayIndexOutofBoundsException is a runtime exception, so you don't have to specify it in the throws clause, although you can.

No comments:

Post a Comment

Chitika