Can someone explain my how this exceptions works?

Viewed 57

I found an really interesting problem on the internet about Exceptions & Errors, but I can't get it.

class MyException extends Exception {
    public function __construct(string $message) {
        $this -> message = $message;
    }
}

class A {
    public function __construct() {
        throw new MyException("an error appeared");
    }
}

$err = null;
try {
    new A();
}
catch (MyException $err) {
    throw new Exception('another error appeared');
}
catch (Exception $err) {
    echo $err;
}

When I execute the code I receive

Fatal error: Uncaught Exception: another error appeared in C:\xampp

I don't understand if it's a problem about the code or this is how it works actually. Maybe you can help me. That fatal error is for an untreated exception? Thank you!

2 Answers

Yes, the fatal error is for an unhandled exception here:

$err = null;
try {
    new A();
}
catch (MyException $err) {
--->throw new Exception('another error appeared');
}
catch (Exception $err) {
    echo $err;
}

In case you are wondering what is leading to this, it is this line in your code snippet:

$err = null;
try {
--->    new A();
}

The second catch block does not catch the exception thrown in the first catch block. It can only be used to catch a an additional type of exception thrown in the first try block. To catch your second exception you need to add a nested try catch:

try {
    new A();
}
catch (MyException $err) {
    try {
        throw new Exception('another error appeared');
    }
    catch (Exception $err) {
        echo $err;
    }
}
Related