• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Exception loss in Java

King Wang

1 月 3, 2022

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. !

发表回复