try block without a matching catch block?
Yes, if there is a finally block. try without catch or finally is a compile-time error.
catch block without a matching try block?No. This is a compile-time error.
finally statement that is not attached to a try-catch block?No. This is a compile-time error.
In general when an unexpected condition occurs. In specific, when you use throw to send a new exception, when the Java library uses throw to send a new exception, or when the Java runtime signals a RuntimeException.
Not necessarily. If an exception isn't caught by the nearest try-catch block, it can be caught higher up. If it's a runtime exception it may not be caught at all.
Use this catch block as the last one in your hierarchy:
catch (Exception e) {
}
If you're in an applet it may be caught in the applet viewer or web browser. However, the most likely result is that the thread in which the exception was thrown will be killed.
catch (NotANumberException) {
System.out.println("Caught a NotANumberException");
}
catch a NotAPositiveNumberException? Yes. Superclasses always catch their subclasses.
Now suppose you have the following catch clause and throw a NotAPositiveNumberException. What happens?
catch (NotANumberException) {
System.out.println("Caught a NotANumberException");
}
catch (NotAPositiveNumberException) {
System.out.println("Caught a NotAPositiveNumberException");
}
"Caught a NotANumberException" is printed on System.out.
catch statement should come first? The one that catches the subclass or the one that catches the superclass? Why?The one that catches the subclass. If the catch block that catches a superclass comes first, then the subclass will never be seen. You should move from the most specific (the subclass) to the most general (the superclass).
Nest try statements and rethrow the exception inside the first catch block, like this
try {
try {
// statements that may fail
}
catch (SubclassException e) {
// handle subclass
throw(e);
}
}
catch (superclass Exception e) {
// handle superclass
}
The throw keyword throws a new exception. The throws keyword declares
that a method may throw a particular exception.
The Character.isJavaLetter() method requires Java 1.1.
public class NotALetterException extends Exception {
static int count=0;
String msg;
public NotALetterException(String s) {
msg = s;
}
public static void countLetter(char c) throws NotALetterException {
if (Character.isJavaLetter(c)) {
count++;
}
else {
throw new NotALetterException(c + " is not a letter");
}
}
}