Showing posts with label throws. Show all posts
Showing posts with label throws. Show all posts

Monday, 27 June 2011

More precise exception rethrow

The more precise rethrow is a tricky one to understand. See if you can spot what the new feature is in the example below. Will it compile on pre-java-7? If not how would it need to be changed to compile on pre-java-7? The answers lie after the example.


public class MorePreciseExceptionRethrow {

static class Exception1 extends Exception {}
static class Exception2 extends Exception {}

public static void main(String[] args) throws Exception1, Exception2 {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception e) {
throw e;
}
}

}


On Java 6 compiling the above gives the following exception.
Foo.java:18: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;
^
1 error

This can be fixed for Java 6 by changing:
public static void main(String[] args) throws Exception1, Exception2 {

to:

public static void main(String[] args) throws Exception {{

So now you see the improvement that Java 7 offers with this feature. You can be more precise in the declaration of the exceptions that you rethrow. Very nice indeed.

Monday, 16 May 2011

throw vs throws in java

throws is used to specify that an exception/s can be thrown. Specifying is more pertinent to checked exceptions.

throw is simply the statement to manually/programically throw the exception or any object of throwable type.

Using throws

a method, and then tell that this method throws following exception…and then write da .. da .. da. Eg.

public void myMethod() throws MalformedURLException,MyCustomException1
{
//do something in method
}



Using throw


throw just throws exception. Eg.

if(something)
throw someObjectOfThrowableType

Saturday, 12 March 2011

throws : 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.

The throw Statement

Syntax of throw

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


What if object is not Throwable ?

If you attempt to throw an object that is not throwable, the compiler refuses to compile your program and displays an error message similar to the following:

testing.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable.
throw new Integer(4);
^

The next page, The Throwable Class and Its Subclasses, talks more about the Throwable class.


Example



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


public Object pop() throws EmptyStackException {
Object obj;
if (size == 0)
throw new EmptyStackException();
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}

The pop method checks to see if there are any elements on the stack. If the stack is empty (its size is equal to 0), then pop instantiates a new EmptyStackException object and throws it. The EmptyStackException class is defined in the java.util package. Later pages in this lesson describe how you can create your own exception classes. For now, all you really need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.

The throws Clause





You'll notice that the declaration of the pop method contains this clause:



throws EmptyStackException

The throws clause specifies that the method can throw an EmptyStackException. As you know, the Java language requires that methods either catch or specify all checked exceptions that can be thrown within the scope of that method. You do this with the throws clause of the method declaration. For more information about this requirement see Java's catching or throwing exception. Also, Specifying the Exceptions Thrown by a Method shows you in more detail how a method can specify the exceptions it can throw.





throw vs throws


See here for the difference between throw and throws.