Of course ,Java There are also flaws in . Exception as a flag for program errors , It should never be ignored , But it can still be easily ignored .
Use… In some special way finally Clause , That’s what happens :
class VeryImportantException extends Exception{
public String toString() {
return "A very important exception";
}
}
class HoHumException extends Exception{
public String toString() {
return "A trivial exception";
}
}
public class LostMessage {
void f() throws VeryImportantException{
throw new VeryImportantException();
}
void dispose() throws HoHumException{
throw new HoHumException();
}
public static void main(String[] args) {
try {
LostMessage lm = new LostMessage();
try {
lm.f();
}finally {
lm.dispose();
}
}catch(Exception e) {
System.out.println(e);
}
}
}
Output results :
From the output , We can see :VeryImportantException Be missing , It has been finally In Clause HoHumException replaced .
This is a very serious defect , Because exceptions can be lost in a more subtle and imperceptible way than in the previous example .
A simpler way to lose exceptions , It’s from finally Clause returns :
After this program runs , We can see that even if an exception is thrown , It also doesn’t produce any output .
public class ExceptionSilencer {
public static void main(String[] args) {
try {
throw new RuntimeException();
}finally {
return;
}
}
}
Thank you. !