• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about exception

 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Unchecked {
public static void main(String[] args) {
try {
method();
} catch (Exception e) {
}
}
static void method() {
try {
wrench();
System.out.println("a");
} catch (ArithmeticException e) {
System.out.println("b");
} finally {
System.out.println("c");
}
System.out.println("d");
}
static void wrench() {
throw new NullPointerException();
}
}
the code above does compile.What confuse me is
static void wrench() {
throw new NullPointerException();
}
I think it should be
static void wrench() throws NullPointerException {
throw new NullPointerException();
}
[ March 06, 2002: Message edited by: michael wang ]
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The name of your class, Unchecked, explains your situation.
In java, there is a special class of Exceptions, called unchecked exceptions. They all descend from/extend RuntimeException. RuntimeExceptions do not have to be declared like other types of exceptions. You can freely throw a RuntimeException without declaring that you do so. That's why you don't need to include the "throws NullPointerException" clause. It is of course perfectly legal to include it if you want to; but it's not mandatory, since it's an unchecked exception.
 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
very clear,thanks
it's really very important to read it again and again.
 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thought I'd complete Rob's message.
Though this does not directly impact your question, but still for clarity's sake...
UnChecked exceptions comprise of the RuntimeException & its subclasses AND
Error & its subclasses.
So, even if you throw an exception which is of type Error or one of its subclasses, you wouldn't have to declare it as being thrown.
- Himanshu
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To banter on, I'd like to make relate this to something you're probably even more familiar with, arrays. When you use the [] operator on an array to get a value from the array, this operator has the ability of throwing an ArrayIndexOutOfBoundsException. Yet, you don't have to catch it. If you did, every time you wanted to get something out of an array, you'd have to do this:

If you take a look at ArrayIndexOutOfBoundsException in the API, you'll see that it descends from RuntimeException, meaning that it is unchecked. Therefore, the try block I showed above, although perfectly legal, is optional.
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic