Ben böyle bir şey bakarak kod tökezledi:
void run() {
try {
doSomething();
} catch (Exception ex) {
System.out.println("Error: " + ex);
throw ex;
}
}
void doSomething() {
throw new RuntimeException();
}
Bu kod beni şaşırtıyor çünkü run()-method bir fırlatma yeteneğine sahip gibi görünüyor Exception, çünkü onu yakalayıp Exceptiondaha sonra tekrar atıyor , ancak yöntemin atılacağı bildirilmedi Exceptionve görünüşe göre olması gerekmiyor. Bu kod iyi derlenir (en azından Java 11'de).
Benim beklentim -tode ilan etmek throws Exceptionzorunda run()kalacaktı.
Ek bilgi
Benzer şekilde, eğer doSomethingatmak ilan edilir IOExceptiondaha sonra sadece IOExceptionbeyan edilmesi gerekmektedir run()rağmen, kullanılan yöntem Exceptionyakalandı ve rethrown edilir.
void run() throws IOException {
try {
doSomething();
} catch (Exception ex) {
System.out.println("Error: " + ex);
throw ex;
}
}
void doSomething() throws IOException {
// ... whatever code you may want ...
}
Soru
Java genellikle netliği sever, bu davranışın arkasındaki neden nedir? Hep böyle miydi? Java Dil Spesifikasyonu'ndaki nedir, run()yöntemin throws Exceptionyukarıdaki kod snippet'lerinde bildirilmesine gerek yoktur ? (Eğer eklersem, IntelliJ beni Exceptionasla atılmadığı konusunda uyarır ).
-source 1.6bayrağın derlenmesi beklendiği gibi bir derleme hatası oluşturur. Kaynak uyumluluğu 7 ile derleniyor yok değil derleme hatası yükseltmek
In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions : 1. 1. The try block is able to throw it. 2. There are no other preceding catch blocks that can handle it. 3. It is a subtype or supertype of one of the catch clause's exception parameters.
javac- Eclipse derleyicisinin daha yumuşak olduğu durumlarda çalışıyorum.