/*** Return Whether the given Throwable is a checked exception: * That's, neither a runtimeexception nor an ERR Or. * @paramex the Throwable to check *@returnwhether the throwable is a checked exception *@seejava.lang.Exception *@seejava.lang.RuntimeException *@seeJava.lang.Error*/ Public Static Booleanischeckedexception (Throwable ex) {return! (exinstanceofRuntimeException | | ExinstanceofError); } /*** Check Whether the given exception is compatible with the specified * exception types, as declared in a thro WS clause. * @paramex The exception to check *@paramdeclaredexceptions The exception types declared in the throws clause *@returnwhether the given exception is compatible*/ //if ex is runtimeexception or error, then it is compatible, if EX is a subclass of a class declaredexceptions Public Static BooleanIscompatiblewiththrowsclause (Throwable ex, class<?>... declaredexceptions) { if(!ischeckedexception (ex)) {//true if ex is runtimeexception or error return true; } if(Declaredexceptions! =NULL) { for(class<?>declaredexception:declaredexceptions) { if(Declaredexception.isinstance (ex)) {return true; } } } return false; }
Iscompatiblewiththrowsclause where is this method used? Used in a check that throws a specified type of exception, such as a method that can be called if only a certain exception is thrown to handle it.
Public Static voidTest () {Try { intA = 1/0; } Catch(Exception e) {if(Iscompatiblewiththrowsclause (E, nosuchfieldexception.class)){ //if it's nosuchfieldexception, check for exceptions .//the problem is that run-time exceptions and errors are also handledSYSTEM.OUT.PRINTLN ("to process"); } } }
Java checks if the thrown exception is an inspection exception or run-time exception or error to be captured
Java checks if the thrown exception is an inspection exception or run-time exception or error to be captured