== Why is this an issue?

A `try-catch` block is used to handle exceptions or errors that may occur during the execution of a block of code. It allows you to catch
and handle exceptions gracefully, preventing your program from terminating abruptly.

The code that may throw an exception is enclosed within the `try` block, while each `catch` block specifies the type of exception it can
handle. The corresponding catch block is executed if the exception matches the type specified in any catch block. It is
unnecessary to manually check the types using `instanceof` because Java automatically matches the exception type to the appropriate catch
block based on the declared exception type in the catch clauses.

== How to fix it

Replace `if` statements that check the exception type using `instanceof` with corresponding `catch` blocks.

=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
try {
  /* ... */
} catch (Exception e) {
  if(e instanceof IOException) { /* ... */ }         // Noncompliant
  if(e instanceof NullPointerException{ /* ... */ }  // Noncompliant
}
----


==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
try {
  /* ... */
} catch (IOException e) { /* ... */ }                // Compliant
} catch (NullPointerException e) { /* ... */ }       // Compliant
----


== Resources

* https://wiki.sei.cmu.edu/confluence/display/java/ERR51-J.+Prefer+user-defined+exceptions+over+more+general+exception+types[CERT, ERR51-J.] - Prefer user-defined exceptions over more general exception types
* https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html[Oracle - Exceptions]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Replace the usage of the "instanceof" operator by a catch block.


'''
== Comments And Links
(visible only on this page)

=== on 16 Aug 2013, 08:27:16 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-292

endif::env-github,rspecator-view[]
