1

I have written a very simple code to catch an exception in PHP but it still shows an error on the page . I am not able to understand why it does not catch the exception .

<?php

try
{
    session_start();

    echo    ($counter);
}
catch(Exception $e)
{
    echo "caught exception";
}

?>
6
  • 2
    This is not exception. This is a fatal error. fatal errors can't be handle by try catch block Commented Jan 11, 2018 at 10:18
  • So exception class wont catch a fatal error ? that is what they are for , right ? Commented Jan 11, 2018 at 10:20
  • yes, exception class wont catch the fatal errors Commented Jan 11, 2018 at 10:21
  • Possible duplicate of PHP: exceptions vs errors? Commented Jan 11, 2018 at 10:26
  • @yivi I dont think the question explains why exceptions wont catch fatal errors? Commented Jan 11, 2018 at 10:31

1 Answer 1

2

Before php 7 you could only catch exceptions, not errors, but since php 7 you have a new interface called \Throwable that is more general than just exceptions and also the Error class was introduced that implements Throwable

http://php.net/manual/en/class.throwable.php

There are currently two types of Throwable objects, that is Exceptions and Errors, So now you can also catch Errors, However Fatal errors still break your code

you can try

<?php

try
{
    session_start();

    echo    ($counter);
}
catch(\Exception $e)
{
    echo "caught exception";
}
catch(\Error $e)
{
    echo "caught error";
}

or you car try

try
{
    session_start();

    echo    ($counter);
}
catch(\Throwable $e)
{
    echo "caught exception";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.