- As we discussed before,not handling checked exceptions would lead to compilation failures,unlike runtime exceptions
throw new Exception();
}
This is CE (for here onwards,I'll refer it CE=compilation error:P )
- Creating Exceptions,
- See throws clause as a filter (like we saw try - catch as nets ).They inform an exception may come.
- Q)
static void A() throws Exception{
System.out.print("A");
throw new Exception();
}
static void B(){
System.out.print("B");
A();
System.out.print("C");
}
public static void main(String[] args) {
try {
System.out.print("D");
B();
System.out.print("E");
} catch (Exception e) {
System.out.print("caught");
}
}
}
what would be the output?
Output would be D B A then CE.
So how can we avoid the CE? simply adding a filter (throws clause) at B method or putting a net (try - catch block) at A or B methods.
- What happens at method overriding then? Easy,two simple rules
* If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can
declare unchecked exception.
If the superclass method declares an exception
* If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but cannot
declare parent exception.
- You get an ExceptionInInitializerError if something goes wrong in the static initializer block.
class C
{
static
{
// if something does wrong -> ExceptionInInitializerError
}
}
0 comments:
Post a Comment