What is the advantage of using try {} catch {} versus if {} else {}

PhpMysqlPdo

Php Problem Overview


I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.

What is the advantage of that method, can I use one try / catch block instead of several nested if / else blocks to handle all errors for the different steps (connect, prepare, execute, etc.)?

Php Solutions


Solution 1 - Php

I'd use the try/catch block when the normal path through the code should proceed without error unless there are truly some exceptional conditions -- like the server being down, your credentials being expired or incorrect. I wouldn't necessarily use it to handle non-exceptional errors -- say like the current user not being in the correct role. That is, when you can reasonably expect and handle an error that is not an exceptional condition, I think you should do your checks.

In the case that you've described -- setting up and performing a query, a try/catch block is an excellent way to handle it as you normally expect the query to succeed. On the other hand, you'll probably want to check that the contents of result are what you expect with control flow logic rather than just attempting to use data that may not be valid for your purpose.

One thing that you want to look out for is sloppy use of try/catch. Try/catch shouldn't be used to protect yourself from bad programming -- the "I don't know what will happen if I do this so I'm going to wrap it in a try/catch and hope for the best" kind of programming. Typically you'll want to restrict the kinds of exceptions you catch to those that are not related to the code itself (server down, bad credentials, etc.) so that you can find and fix errors that are code related (null pointers, etc.).

Solution 2 - Php

In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen.

Edit: Also, catch blocks won't stop your code from halting when an error is hit.

Solution 3 - Php

The advantage of try/catch, and exceptions in general, is more for the people developing libraries like PDO. They allow a system developer to handle undefined situations or unexpected results in a quick and easy way. Take a database connection. What should a system do if the database can't be reached. Should it halt execution? Try again? Throw a warning and continue? The system developer can't know what you'll need it to do, they they throw an exception, which you'll later catch and handle.

The advantage for you, as a consumer of the system is rather than getting some vague error code back, or a simple boolean false that it failed, you get an Exception object which will

  1. Be named in such a way that it's more obvious what went wrong (If I remember right, PDO only has one Exception type, but other systems contain multiple exception types for different kinds of errors)

  2. May/should contain methods and properties which can help you figure out why the exception was thrown

That's the theory anyway. There are lots of smart people who claim Exceptions are the way to go. There are also lots of smart people who think Exceptions are the devil, and a crutch for lazy system developers. There is nothing resembling consensus on this issue.

Solution 4 - Php

@Perchik:

My general philosophy of error handling:

You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it. You should use try {} catch {} in situations where you suspect something can/will go wrong and you don't want it to bring down the whole system, like network timeout/file system access problems, files doesn't exist, etc.

http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx">Vexing exceptions

Solution 5 - Php

Throwing and catching an exception is an expensive operation compared with most any other primitive operation. If this is a piece of code that needs to perform well (eg, in a tight loop), you will want to look at your use case - if you expect the exceptions to be thrown relatively often, you will be better off with an if/else perforance-wise (unless the underlying code is just wrapping an exception for you, in which case there's no gain at all). If the exceptions are only thrown in rare circumstances, then you're better off with a try/catch to avoid the overhead of branching in a tight loop.

Solution 6 - Php

Try/Catch totally separates the error handling logic from the object business logic.

Solution 7 - Php

That’s exactly the advantage, using one try/catch instead of multiple if statements. You will also be able to catch any unanticipated errors.

Solution 8 - Php

Everybody else had good answers - but I figured I would throw my own in:

  1. Try/Catch is an actual exception handling mechanism - so if you change your exceptions, it will automatically work on all try/catch statements.
  2. Try/Catch gives the opportunity to run code even in the case of a major exception that might kill the if/else and in addition, the try statement can be rolled back (if you're savvy).

Solution 9 - Php

Since PDO is using objects, they are raising Exceptions if an error occur. The old mysql/mysqli were mere functions and didn't throw Exceptions they simply returned error codes. Try/catch is used when an Exception can be thrown from the code, and you catch it in the catch-clause, which is an object oriented way to handle errors. You can't catch Exceptions with if/else blocks - they share nothing with try/catch.

Solution 10 - Php

In php by using Try Catch with inheritence, We can throw exception from another class.

Example :- I am in the controller and validating user data by using Models.

If any error triggers, I just have to throw exception from Model methods.

The execution in try will break and catched in the Catch Block.

So There is less overhead of returning bool vales and checking that.

Apart from this Try Catch works great When using in chain ( Try - Catch inside another Try - Catch ).

Solution 11 - Php

This question has been asked more than a decade ago out of the wrong premise. In reality if and try are incomparable matters. Sadly, but up to this day people catastrophically confuse exceptions with try catch, thinking one is inseparable from another.

In the way it is asked, indeed it makes very little sense to change if {} to try {} in the meaning of obligatory try wrapping a single line of code to test for the error.

However the actual question is What is the advantage of using exceptions versus if {} else {}.

And it starts to make a whole world of sense immediately: exceptions allow automated error reporting, when neither try catch nor if else is ever have to be written.

An exception is essentially an automated way to write if ($result == FALSE) raise_error(); Without exceptions you are bound to test every operation's result manually. It would be just stupid to recreate the same behavior using exceptions. In most cases a thrown exception should be left alone, unless there is a certain handling scenario. In all other cases it has to bubble up elsewhere, hence no try {} catch {} has to be written.

Solution 12 - Php

Let's say we are writing an a/b division code and the most famous exception case has occurred i.e. 0 divide error, what do you think can be done next?

  1. You can print a message and exit.
  2. You can print a message and let the user re-enter the values, etc.

There are cases when different people/vendors want to handle the same exception case in different way. The catch block let them do this with ease. If you need to change the way how a certain exception case will be handled, you just need to change the catch block.

Solution 13 - Php

TRY/ CATCH can be used within the programming context where you have very little information about the error or you think that might can occur such as.

#include <iostream>
using namespace std;

int main (){
    try{
        while(true){
            new int[100000];
        }
    }
    catch(bad_alloc& e){
       cout << e.what() << endl;
     }
 }

Although there are no semantic or compile-time errors in the program, but it's understandable that it posses a run-time error which is "bad_alloc" which appears when you try to continuously allocate the memory and your program run out of memory. This exception is defined in bad_alloc standard class which is a child-class of class "Exception", since it throws an implicit exception, throw keyword is not implied here.

You can also use try/catch to check if the file is accidentally deleted and can use if/else to check if there exists a file or not, both have their own advantages.

Solution 14 - Php

Try and Catch functions are useful whenever there is a communication between functions. In Try and Catch , if there exists an exception in the TRY block, the control is transferred directly to the CATCH block which would store our exception condition. This however is not possible in case of IF ELSE, where in IF condition , if there exists an exception, the control cannot go to the ELSE block howsoever in any case.

int division(int a,int b){
    if(b==0)
       throw 101;
    return a/b;
}

int main()
{
    int a=10,b=0,c;
    try{
        c=division(a,b);
        cout<<c<<endl;
    }
    catch(int a){
        cout<<"Division not possible by 0"<<endl;
   }
}

Consider the following Code: throw and catch function is used for communication between functions division and the main function. Note that the statement to print c is not executed when b is 0 as the control directly transfers to the catch block after the value os thrown. This however would not have been possible , had it been IF ELSE here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeroenView Question on Stackoverflow
Solution 1 - PhptvanfossonView Answer on Stackoverflow
Solution 2 - PhpPerchikView Answer on Stackoverflow
Solution 3 - PhpAlan StormView Answer on Stackoverflow
Solution 4 - PhpJared UpdikeView Answer on Stackoverflow
Solution 5 - PhpNot SureView Answer on Stackoverflow
Solution 6 - PhpTrapView Answer on Stackoverflow
Solution 7 - PhpShaun HumphriesView Answer on Stackoverflow
Solution 8 - PhpAdam NelsonView Answer on Stackoverflow
Solution 9 - PhpBjörnView Answer on Stackoverflow
Solution 10 - PhpAmit SinghView Answer on Stackoverflow
Solution 11 - PhpYour Common SenseView Answer on Stackoverflow
Solution 12 - Phpxscorp7View Answer on Stackoverflow
Solution 13 - PhpAshmal VayaniView Answer on Stackoverflow
Solution 14 - PhpAviral YadavView Answer on Stackoverflow