I know that each java class should extend the Throwable class so that exceptions can be handled. Is this done by:
public class Test extends Throwable
or
public class Test throws Throwable?
I know that each java class should extend the Throwable class so that exceptions can be handled. Is this done by:
public class Test extends Throwable
or
public class Test throws Throwable?
Primitive types, or object whose class doesn’t extend Throwable cannot be thrown as exceptions.
Interpretation:
throw 3;
doesn't work because 3 is a primitive type.
throw new String();
doesn't work because String
doesn't extend Throwable
.
throw new RuntimeException();
works because RuntimeException
is a subclass of Throwable
.
When a class extends a Throwable, the class is a sub-class of Throwable and you can throw this class as a Throwable anywhere in you code.
class MyCoolThrowable extends Throwable{
try {
//... some error ...
} catch (MyCoolThroable t) {
//... handle the throwable
}
}
You add throws Throwable to a constructor or method so that the code that calls your constructor/method will be forced to use try-catch
void mySweetMethod() throws Throwable {
//...
}
try {
mySweetMethod();
} catch(Throwable t) {
//... handle it here
}
I think this clarified what you have read:)
I know that each java class should extend the Throwable class so that exceptions can be handled.
No, someone lied to you.
To handle exceptions, you need to keep in mind two things:
If it's a checked exception, then the class will refuse to compile if there is not a try...catch
block wrapping the dodgy code, or if you don't declare the exception to be thrown.
try {
File f = new File("Foo.txt");
} catch (FileNotFoundException f) {
System.out.println("File doesn't exist!");
}
or:
public void doDodgyStuffWithFile throws FileNotFoundException { }
If it is an unchecked exception, then you will not get a compile-time failure for not catching the dodgy code, but you may get runtime exceptions from it.
String input = scanner.nextLine();
System.out.println(Integer.parseInt(input));
If you are throwing or catching the exception, be as specific as possible. Do not give into the temptation to throw/catch Exception
, and never catch a Throwable
.