Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Unreachable catch clause

ID: java/unreachable-catch-clauseKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - correctness   - exceptions   - external/cwe/cwe-561Query suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

An unreachablecatch clause may indicate a logical mistake in the exception handling code or may simply be unnecessary.

Although certain unreachablecatch clauses cause a compiler error, there are also unreachablecatch clauses that do not cause a compiler error. Acatch clauseC is considered reachable by the compiler if both of the following conditions are true:

  • A checked exception that is thrown in thetry block is assignable to the parameter ofC.

  • There is no previouscatch clause whose parameter type is equal to, or a supertype of, the parameter type ofC.However, acatch clause that is considered reachable by the compiler can be unreachable if both of the following conditions are true:

  • Thecatch clause’s parameter typeE does not include any unchecked exceptions.

  • All exceptions that are thrown in thetry block whose type is a (strict) subtype ofE are already handled by previouscatch clauses.

Recommendation

Ensure that unreachablecatch clauses are removed or that further corrections are made to make them reachable.

Note that if atry-catch statement contains multiplecatch clauses, and an exception that is thrown in thetry block matches more than one of thecatch clauses, only the first matching clause is executed.

Example

In the following example, the secondcatch clause is unreachable. The code is incomplete because aFileOutputStream is opened but no methods are called to write to the stream. Such methods typically throwIOExceptions, which would make the secondcatch clause reachable.

FileOutputStreamfos=null;try{fos=newFileOutputStream(newFile("may_not_exist.txt"));}catch(FileNotFoundExceptione){// ask the user and try again}catch(IOExceptione){// more serious, abort}finally{if(fos!=null){try{fos.close();}catch(IOExceptione){/*ignore*/}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp