Try catch внутри try catch php

Confused by this PHP Exception try..catch nesting

The exception handlers catch exception raised by code inside the scope of their try block.

The call to $a->somethingElse() does NOT occur within the try block associated with the skipped exception handler. It occurs within another catch clause.

Just because it appears physically below the line that raises the exception isn’t enough to make it cover that code.

The style choice of indenting braces makes this less clear, IMHO. The close brace for the previous try block appears on the same line as the next catch, even though they are unrelated (well, sibling) scopes.

I just want to be sure we’re on the same page. Basically he should have added another try after the first catch , right? Then, because the entire thing is embedded in the larger try, he would get 3 sets of exceptions? Essentially it never catches the second exception because it never tries?

If he had, alternatively, changed the outer catch to «MyException» instead of «Exception» would this have caught the «MyException» throw ? Is the issue that his attempt triggers the throw of «MyException» but because the attempt wasn’t initiated by a try , the catch never happens? In other words, is «MyException» still out there to be caught by that third catch ?

Читайте также:  Название страницы

@Anthony, re: First comment: Yes, if he added a third level of try block that would be one solution. Bit messy though. I wouldn’t choose to characterise the problem as you have in your last sentence, but it isn’t wrong.

@Anthony, re: 2nd comment, 1st question: Yes, if he changed the outer catch as your describe, it would catch the exception, but the outer catch is ALREADY catching the exception! It is catching it as a Exception rather than as a MyException, but it is the same exception!

Источник

How to pass the exception caught in inner catch to outer catch in a nested try catch

I am nesting try catches inside of a main try catch statement, what I would like to know is how I can make the main try catch fail if one of the nested try catches fails? Here is my code:

try < try < //how can I make the main try catch fail if this try catch fails? >catch(Exception $e) < error_log(); >> catch(Exception $e)

5 Answers 5

After error_log(); in the first try-catch, type throw $e; (on a new line). This will throw the error again, and the outer try-catch will handle it.

You should extend Exception for the various different types of Exception. That way you can trigger a specific try-catch block:

try < . try < throwSomeException(); >catch ( InnerException $e ) < . do stuff only for InnerException. >. > catch ( Exception $e )

Additionally, you can chain your catch statements to trigger different blocks in a single try-catch:

try < . >catch ( SpecificTypeOfException $e ) < ..do something specific >catch ( TypeOfException $e ) < ..do something less specific >catch ( Exception $e )

Inside the inner catch, throw() — NOT recommended, I’ve seen several issues with PHP when doing this. Or set a flag to throw just after the inner catch.

Here’s an example throwing the same exception (or you could throw a different one).

try < $ex = null; try < //how can I make the main try catch fail if this try catch fails? >catch(Exception $e) < $ex = $e; error_log(); >if ($ex) < throw $ex; >> catch(Exception $e)

I handle exceptions in a way similar to eventHandling in Javascript. An event bubbles up the ladder from specific to generic. When it reaches the start program, an exception lost all it’s meaning to the code and should simply be caught for logging and ending an application.

In the meantime a lot of stuff can happen

  • Start Lunch
  • Eat Apple (Before this code, an apple was bought as lunch)
  • Sink teeth in apple

During my eating of the apple, a worm appeared:

throw NausiaException('I found a bleeding worm. '); 

the exception because in that scope we can return the apple to the store and shout at the manager. Since nothing more useful can be said about the occurrence,

is called because eating the apple failed.

Something could’ve gone different However, if the store manager refused to refund, you can wrap the exception

throw new RefundFailedException('The manager is a cheap skate', RefundFailedException::REFUSED, $e) 

Start lunch Scope Start lunch scope wants to throw away bad lunch

Источник

PHP Nested Try-Catch

PHP Nested Try-Catch

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. Nested blocks can be useful in case a block of code causes an exception, which can be handled within that block and program execution can continue in the outer block. They can also be useful in case the handling of an exception causes another exception.

Here is an example of a nested try-catch block:

try < try< if(file_exists("myfile.json"))< //upload file >else < throw new Exception( 'File not found'); >> catch (Exception $e) < throw new Exception( 'Unable to upload file',0,$e); >//continue outer try block code > catch (Exception $e)< echo $e->getMessage() . "
"; while($e = $e->getPrevious()) < echo 'Previous exception: '.$e->getMessage() . "
"; > >

In this example, a file is uploaded and it is checked whether the file exists or not prior to the upload operation. If it does not exist, an exception is thrown. This code that checks whether the file exists or not is placed within a try-catch block, which is nested within another try-catch block.

In case the file is not found, the inner block throws an ‘Unable to upload file’ exception, which is caught and handled by the outer block, leading to the following output:

Unable to upload file Previous exception: File not found

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it Today!

Источник

Exception Handling in PHP

How to Handle Exceptions in PHP

How to Handle Exceptions in PHP

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can «try» to execute a block of code, and «catch» any PHP exceptions that are thrown.

PHP nested try-catch

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.

Nested blocks can be useful in case a block of code causes an exception, which can be handled within that block and program execution can continue in the outer block.

They can also be useful in case the handling of an exception causes another exception.

Here is an example of a nested try-catch block:

try < try< if(file_exists("myfile.json"))< //upload file >else < throw new Exception( 'File not found'); >> catch (Exception $e) < throw new Exception( 'Unable to upload file',0,$e); >//continue outer try block code > catch (Exception $e)< echo $e->getMessage() . "
"; while($e = $e->getPrevious()) < echo 'Previous exception: '.$e->getMessage() . "
"; > >

In this example, a file is uploaded and it is checked whether the file exists or not prior to the upload operation. If it does not exist, an exception is thrown.

This code that checks whether the file exists or not is placed within a try-catch block, which is nested within another try-catch block.

In case the file is not found, the inner block throws an ‘Unable to upload file’ exception, which is caught and handled by the outer block, leading to the following output:

Unable to upload file Previous exception: File not found

Catching all PHP exceptions

The simplest way to catch exceptions is through the use of a generic try-catch block. Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front:

Catching specific PHP exceptions

While catching every exception thrown is great for simplistic implementations—such as generalizing API error responses—best practice is to catch for specific PHP exceptions. By using the same type-hinting method shown above in reference to specific exception objects instead of a global exception object, you can react more effectively to individual problems that your application may encounter on the way.

try < // . >catch ( \Custom\Exception $e ) < // . >

Catching just one type of PHP exception isn’t very valuable though, is it? What happens if your application throws a different exception? Much like an if-elseif-else chain, a try-catch block can have multiple catches—which, when combined with a check for the built-in PHP exception class, allows you to logically adapt to any and all issues that may arise:

try < // . >catch ( \Custom\Exception $e ) < // . >catch ( \Other\Exception $e ) < // . >catch ( \Exception $e ) < // . >

The exception handler

While wrapping dangerous code in try-catch blocks is a great way to harden an application against unexpected PHP errors, you can’t always catch everything. Sometimes an exception falls through the cracks, which is where the global PHP exception handler comes into play. This method, dubbed set_exception_handler, provides a fallback for any uncaught exceptions.

set_exception_handler(function($exception) < // . >);

Although you can utilize this method in a number of different ways, it is generally best used for logging and display formatting, as every PHP exception thrown will be caught—not just built-in exceptions—which can result in unpredictable behavior if not used properly.

PHP framework exception handling

While the global exception handler can be used regardless of framework, it is important to know that frameworks like Symfony and Laravel have their own ways of handling PHP exceptions. Laravel, for example, handles all exceptions using a class that defines how exceptions should be reported and rendered. Symfony, on the other hand, uses an event listener to catch exceptions. Both valid ways to handle PHP exceptions, but designed to fit within their own ecosystems.

Check out our blog to see a working example of Laravel error reporting.

Track, Analyze and Manage PHP Errors With Rollbar

Managing errors and PHP exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Learn more about Rollbar’s features for PHP and then sign up for a free trial.

Источник

Оцените статью