I have a question regarding java.lang.Exception and the way it is considered within the throw/throws clauses.
I have the following 2 examples and I don't understand exactly how the java.lang.Exception is handled: as checked or unchecked exception.
The following method compiles successfully:
public double method1() throws Exception {
return 0.7;
}
- here it seems to me that the java.lang.Exception is threaten java.lang.RuntimeException or java.lang.Error. You can declare to throw it even if you don't handle it.
- if instead of an Exception we used a checked exception (that are sub-classes of java.lang.Exception) then you should had to have a throw declaration within the body of the method (or call a method that throws that checked exception). Right?
The following doesn't compile:
private void method2(int age) {
if (age > 30)
throw new Exception();
}
- here is my confusion...if it was throwing a subclass of type java.lang.RuntimeException or java.lang.Error it would had compiled.
- why in this case it doesn't compile ? I guess it is because it threats java.lang.Exception as a checked exception. But if it is so, then why method1 does compile?
Thank you, Luisa