IOException vs RuntimeException Java
class Y {
public static void main(String[] args) throws RuntimeException{//Line 1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws RuntimeException{ //Line 2
if (Math.random() > 0.5) throw new RuntimeException(); //Line 3
throw new IOException();//Line 4
}
}
Cuando lanzo dos tipos de excepción (IOException en Line4 y RunTimeException en Line3), encontré que mi programa no se compila hasta que indique "IOException" en mis cláusulas de tiradas en Line 1 y Line 2.
Mientras que si invierto "lanzamientos" para indicar que IOException está siendo lanzada, el programa se compila exitosamente como se muestra a continuación.
class Y {
public static void main(String[] args) throws IOException {//Line1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws IOException {//Line 2
if (Math.random() > 0.5) throw new RuntimeException();//Line 3
throw new IOException();//Line 4
}
}
¿Por qué debería usar siempre "lanzamientos" para IOException aunque RuntimeException también se lanza (Línea 3)?