Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try catch exceptions

Hello I have a code like that :

try
{
    // Here I call my external function
    do_some_work()
}
catch(Exception $e){}

The question is: If the do_some_work() has a problem and produce an Error this try catch will hide the error?

like image 241
KodeFor.Me Avatar asked Oct 11 '11 09:10

KodeFor.Me


People also ask

What are exceptions in PHP?

An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.

Can I use try catch inside try catch in PHP?

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first.

What is an exception how you can handle multiple exceptions in PHP?

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors (runtime errors are called exceptions). So that the normal flow of the application can be maintained. The main purpose of using exception handling is to maintain the normal execution of the application.


2 Answers

There are two types of error in PHP. There are exceptions, and there are errors.

try..catch will handle exceptions, but it will not handle errors.

In order to catch PHP errors, you need to use the set_error_handler() function.

One way to simplify things mught be to get set_error_handler() to throw an exception when you encounter an error. You'd need to tread carefully if you do this, as it has the potential to cause all kinds of trouble, but it would be a way to get try..catch to work with all PHP's errors.

like image 196
Spudley Avatar answered Oct 13 '22 01:10

Spudley


If do_some_work() throws an exception, it will be catched and ignored.

The try/catch construct has no effect on standard PHP errors, only on exceptions.

like image 36
Sjoerd Avatar answered Oct 13 '22 00:10

Sjoerd