== Why is this an issue?

Exception handling provides a way to help developers handle and recover from runtime errors and unexpected events during program execution.
When an error occurs, an exception is thrown and can be caught by an appropriate try-catch block, allowing the program to handle the exception and prevent the program from crashing.

A problem arises, when an exception or error class -- an instance of `Throwable` -- in a catch clause does not exist, as PHP won't generate an error.

This typically occurs when being in a namespace trying to catch PHP built-in exception classes without escaping to the global namespace or importing the classes.

In summary, this rule raises an issue when, being in a namespace, an undefined class belonging to that namespace is caught.

=== What is the potential impact?

Initially, since the exception is not being caught, it will cause a runtime error in production.

Additionally, this can lead to complex debugging problems as the root cause of the issue may not be obvious.

== How to fix it in Core PHP

Escape the caught exception to the global namespace or import the class.

=== Code examples

==== Noncompliant code example

[source,php,diff-id=1,diff-type=noncompliant]
----
namespace Foo\Bar;

try {
    doSomething();
} catch (Exception $e) { // Noncompliant - Exception will never be caught because the class Exception does not exist in the namespace
    echo $e->message;
}
----

==== Compliant solution

[source,php,diff-id=1,diff-type=compliant]
----
namespace Foo\Bar;

try {
    doSomething();
} catch (\Exception $e) { // Compliant: Used by global namespace
    echo $e->message;
}
----

[source,php,diff-id=1,diff-type=compliant]
----
namespace Foo\Bar;

use Exception;

try {
    doSomething();
} catch (Exception $e) { // Compliant: Imported by use statement
    echo $e->message;
}
----

== Resources

=== Documentation

* https://www.php.net/manual/en/language.exceptions.php[PHP Manual - Exceptions]


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

'''

== Implementation Specification

(visible only on this page)

=== Message

Create class {Exception} or check correct import of class.


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