What Is the Advantage of Using Try {} Catch {} Versus If {} Else {}

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

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.).

How to decide between using if/else vs try/catch?

You should never use try/catch for flow control.

Generating an exception is an extremely expensive action. If/else is much faster and cleaner.

try catch vs if else in PDO and some other things

Exceptions are catchable via try/catch and are classes with properties, while proceedural errors cannot and are not. Proceedural errors are instead handled by PHP's native error handling.

You can observe the behavior difference by manually triggering them.

to throw an Exception:

throw new Exception();

to trigger a proceedural error:

trigger_error($message, U_USER_ERROR);

Exceptions are bassically the OO way of error handling. Find more information about Exceptions here: http://php.net/manual/en/language.exceptions.php

What's the best practice in using if/else as a substitute for try/catch or vice versa?

They are totally different. They are not interchangeable, and which is appropriate is determined by the requirement and context.

EDIT: This answer is based on the original, unedited question. The original, in it's entirety was:

PHP : if/else vs try/catch

which is better

PHP - Does try/catch have a higher overhead than if/then?

The whole point of try/catch is that it is non-local. You can exit multiple loops at a stroke, break out of nested function calls, escape from anywhere you get into. if can't do that, and is not meant to. I do not know about the overhead, but I strongly and informedly suspect that it has much more than if. Ultimately, use the tool right for the job: they are not interchangeable.

Okay, they are, but they shouldn't be interchanged :)

UPDATE: Many other people say that try/catch are for error handling. They are not. They are for exception handling. In many languages, for example, trying to get a next element from the iterator on its last element will raise an exception; this is a perfectly valid use of exceptions. You can use them whenever something unexpected happens, which has to be handled outside the current scope (assuming you are not providing a callback to handle it).

What is the main reason of using try catch?

The main advantage of using a try{} catch(exception){} is that you're able to shift control to the catch(exception){} in the event that an exception is thrown, which allows you to continue processing, as opposed to your script failing miserably. In short, you're catching the exception.

In other words, the main reason is to catch an exception, and then decide what action you'd like to take. Is it possible that you can you approach the problem in a different way and complete the task without failing? If so, that's where catch(exception){ // do something different } comes into play. In a manner of speaking, it offers you a second chance :-)

If statements vs. Try/Catch for checking against array bounds

Interestingly enough, your question is not language independent on the one hand.

In languages such as C, Java, C++, C# ... people prefer the "LBYL" (Look Before You Leap) pattern; whereas languages such as python heavily emphasize "EAFP" (it's Easier to Ask Forgiveness than Permission).

Meaning: in python, you are using try/catch a lot (even the "counting for loop" is implemented as try/catch); whereas in C# you would prefer doing if/else instead.

And these conventions are really important to follow - most Cx-language programmers simply assume that you don't use try/catch to model control flow.

But coming back to your core requirements: go for if/else. As you are pointing out that performance very well might be an issue; you simply want to avoid the more expensive try/catch solution.

And as said; as nice side effect of doing so, your code will be "more mainstream"; thus readers of your code won't give you to many WTFs per minute.

code quality by WTFs per minute

Which is faster, try catch or if-else in java (WRT performance)

It's not a question of which is faster, rather one of correctness.

An exception is for circumstances which are exactly that, exceptional.

If it is possible for n to be null as part of normal business logic, then use an if..else, else throw an exception.

Want to use IF/Else statement in Try/Catch block

If you only want to put a date time stamp in a csv file, if you had a successful passing of the statements in the try block.
You can just put the stamping as the last command in the try block.

Here is a break down:

Errors in the Try block: Each statement will be executed sequentially until there is a error.

Then the remaining statements in the Try block will not be executed.
Instead the Catch block will be executed.

No errors in the Try block:
All the statements in the Try block will be executed.

The Catch block will not be executed.

The Finally block
Will always be executed!!
You normally use this block for cleaning up.
if you open a connection to the database or a open a file in the try block.
you close the connection or the file in the Finally so you are sure that you closed every thing properly.

Tips
If you want to be sure you catch every error in Try block you better use somting like the following:

Try
{
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'

Statement 1
Statement 2
Statement 3
Statement ...
}
Catch
{
Errorhandling
}
Finally
{
$ErrorActionPreference = $OldErrorActionPreference
}

Or you have to use the "-ErrorAction Stop" parameter with each important statement.

you can find more about errorhanding Here



Related Topics



Leave a reply



Submit