Ommiting $ex variable in try-catch block - php

try {
} catch (\Exception $ex) {
}
In my sample use case, I don't need any information from $ex when \Exception is catched. I just need to do some stuff when \Exception is catched. I need nothing from $ex.
Now ommiting $ex causes syntax error, leaving it usued makes my IDE (Netbeans) throw a warning.
Any way to omit $ex other than $ex = '';?

You can't omit the hinted argument \Exception $ex from the catch statement, because the block needs to know what type of Exception it's there to deal with, even if your code doesn't care.
You don't, however, need to refer to it at all in the catch block. If the NetBeans warning hint about the unused variable is really bothering you, you can always silence all hints of that class by going to
Tools -> Options
"Editor" tab
"Hints" sub-tab
Language: PHP
Uncheck "Unused Variables" in list
(Of course then you won't see warnings if you have other unused variables, but if you just want the hints not to be Warnings, you can always change the "Show as:" setting to "info" instead.)

In php there is way of handling error. Because of that catch expect to have store exception. So you have to provide $ex. But you can leave empty inside catch in your case.
To remember this is the syntax.
try {
// run your code here
}
catch (exception $e) {
//code to handle the exception
}
finally {
//optional code that always runs
}

Related

Why does the "catch" in try catch declare type of $e

try {
} catch (Exception $e) {
}
I thought PHP had type inference. Why is it neccesary to declare the type of the variable --$e-- ?
The code can throw different classes of exceptions. You can use that to your advantage to add proper code for error handling.
A try block can be followed by any number of catch blocks.
Example:
try
{
}
catch(\PDOException $e)
{
// Something bad happened while dealing with database
}
catch(\LengthException $e)
{
// Length exception occurred
}
catch(\Exception $e)
{
// The \Exception is the parent class for all exceptions, this handles anything not caught in above example
}
Using the above sample, you can take proper measures for handling errors depending on why they occurred. That means you can throw exceptions that you defined. It's the best if you don't overdo it and swap out entire error handling with exceptions. Exceptions occur when something abnormal in the code flow occurs, for example - a connection to MySQL broke mid-transaction.

Understanding try and catch

This probably sounds ridiculous. However, if you don't ask you'll never learn.
I'm relatively new to PHP and self-taught so I haven't exactly learnt everything "to the book".
Is the following required:
try {
}
catch {
}
Am I right in thinking that the try will try to "execute" the code within the brackets and the catch will try and catch the result of the outcome? If there is nothing to catch then it will throw an error?
The first assumption is correct: the code in try will be attempted to run.
However, if no error is thrown, then the block exits normally. If there is an error thrown, then the try execution ends early and goes into the catch block. So your second idea is switched.
try catch is used for exception handling or error handling.Put your script in try block and write your custom error message in catch block.
try{
// put here script
}catch(Exception $error){
//your custom message
echo 'Caught exception: ', $error->getMessage(), "\n";
}
If your script does not execute then it will be jump catch block and access message using $error object.
What is the benefit? The benefit is the whole script will not be stop to execute. It will be continue other block.
In the try block you execute code, whenever something fails in that block it will jump to the catch block. You usually define a variable holding the exception.
So to answer your question, no it will not process the catch block when there is nothing going wrong in the try block. (unless you specifically throw an exception)
try {
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Try block is hold the code which you want to execute. and Catch block is hold the code if you have cause any error then it will execute the catch code or error message.
Basically try and catch we are using for the error handling and avoid to break the control flow of the program and page.
Simple example:
<?php
class A {
public function getA($a = 0)
{
if ($a === 0) {
throw new ItCantBeZeroException("Message");
}
return $a;
}
}
// I want to throw default exception because I'm not sure
// am I doing it right or what can I do with bad parameter.
$a = new A;
echo $a->getA(0);
// Now, I know what I can do if developer write bad input.
// It can't be 0, so I just print my custom error message
// to my page.
try {
$a = new A;
echo $a->getA(0);
} catch (ItCantBeZeroException $e) {
echo "Parameter can't be zero. Try again.";
}
?>
You can define your own exceptions (like ItCantBeZeroException). Exceptions throw error on site (like "Message") but we can catch them and change to something we want.
You write simple class where some code must be string or integer between 0 and 20.
You use this code, but when user make variable 21, simple class throw error.
You refactor code to catch exception and try to fix code, e.g. change any integer greater than 20 to 20. Then code works properly.
Try and Catch is known as Exception Handling
According to w3schools:
Exceptions Handling are used to change the normal flow of a script if a specified error occurs.
For More:
http://www.w3schools.com/php/php_exception.asp

Custom messages for php exception handling

I'm using an external file with $errmsg array for displaying errors, like:
'app_init' => 'Cannot initialize application',
Using conditionals, I call the function to display the message on failure:
if(!$condition)
{
$arraywithmessages->functionforfiltering($err,'app_init',$aim);
}
...where $err is the array of messages, and $aim is predefined method of publishing error (e-mail, view, etc...)
Now I'd like to make use of Exception Handling, but I don't know where to start. Can anyone help? This doesn't seem to work:
try {
if (!$condition) {
throw new Exception('app_init');
}
// continue
} catch (Exception $e) {
$arraywithmessages->functionforfiltering($err,$e->getMessage(),$aim);
}
I don't know exactly what you want to achive but you should remember that try, catch should be used wisely. It should be used for Exceptional situations only. If you don't use them in that way then it's GOTO code.
About exceptions, remmeber that you can extend Exception class and make your own exceptions and catch them in multiple catch blocks, there is also finally block.
About the constructor of Exception. It has the second param which is $code you can use it to show proper message.
$err = array(0x1 => 'my error app init');
try {
if (!$condition) {
throw new Exception('app_init', 0x1);
}
// continue
} catch (Exception $e) {
echo $err[$e->getCode()]; //it shouldn't be only echo it should do some tries to fix the code close streams etc. not just echo.
}
There is also function
set_exception_handler(). which:
Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.
Consider using it. There are a lot of things that can be found in manual.

Include $_POST, $_GET, $_SERVER values in PHP Error Log

I have code like this
try {
header("Location: http://www.google.com\n-abc");
}
catch (Exception $e) {
error_log(print_r($_POST, true));
error_log(print_r($_GET, true));
error_log(print_r($_SERVER, true));
}
Without the try {} catch {} block, I can see the POST, GET and SERVER variables in my error_log, but with the try {} catch {} block, I only see the default PHP error.
Is there a way to show the POST, GET, and SERVER variables in a try {} catch {} block?
Is there a way to have PHP include POST, GET, and SERVER variables for ALL errors that get logged to file and not just wherever I have added error_log(print_r($_POST, true)); ....?
try/catch is for when you want to throw an exception to prevent php fatal errors from killing the page or to make debugging easier, generally speaking. This is how you would use a try/catch:
try {
if($a === true)
{
header("Location: http://www.google.com\n-abc");
}
else
{
throw new Exception('$a was not true');
}
}
catch (Exception $e) {
error_log(print_r($_POST, true));
error_log(print_r($_GET, true));
error_log(print_r($_SERVER, true));
echo $e->getMessage(); // $a was not true
}
The reason you don't see your error logs in the catch block in your example is because you never threw an exception so PHP will never look inside that catch block to log your variables.
If you simply want to get your example to work you'd just throw an exception to get PHP in that catch block:
try
{
throw new Exception('redirecting...');
}
catch (Exception $e)
{
error_log(print_r($_POST, true));
error_log(print_r($_GET, true));
error_log(print_r($_SERVER, true));
header("Location: http://www.google.com\n-abc");
}
That's just silly though :)
But default PHP functions like header will not throw exceptions.
If you want them to throw exceptions you will need to set the error handler to use ErrorException:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
I think you have a few questions/issues here.
First, a try/catch block is used for Exceptions. The catch {} code is only executed if a Exception of the type specified is thrown.
Second, the header() function does not throw exceptions. Instead it just generates a PHP error directly.
Thirdly, to log those variables for all errors take a look at set_error_handler(), which should also take care of the above, second issue.
try/catch would only work if you're using an object that actually throws exception. header() is NOT an object and will NEVER throw an exception. Like I said in my answer to your previous version of this question, you need to set up a custom error handler.
That's how try/catch is supposed to work: the catch block executes when an exception is thrown in the try block (and only in that case).
The header() function may generate a warning if headers are already sent, but it will never throw an exception.
Answering your questions:
Your catch block is just fine but you need code that can actually throw exceptions (typically object-oriented code, but not necessarily). However, you can configure PHP to convert regular errors into exceptions if you use set_error_handler() to create a custom error handler and use throw inside of it.
Same as above: set_error_handler() and set_exception_handler().
Sounds like you want to have some extra information output to your log when an error is thrown. You should check out custom error handling in PHP. You can define specific ways to handle errors in your scripts and add functionality that is not there by default.PHP Set error handler

Exceptions in PHP. How to use them? How to extend 'em?

Few days ago I deal with errors like this...
exit( 'Error!' );
or exit( 'Error!' );
Doh, right? =] Now I'm trying to learn Exceptions. This is how far I got...
http://pastie.org/1555970
Is that correct use of them? It would be cool that I can have more info about 'em. Like file where exception is thrown and line of that file. I know that there are build-in methods (in Exception class), but I want to somehow extend it so I don't need to write...
throw new My_Exception( '...' );
catch( My_Exception $e ) {
echo $e->my_method();
}
...but use old syntax.
throw new Exception( '...' );
catch( Exception $e ) {
echo $e->getMessage();
}
...or maybe you have any greater thought of Exceptions? How to deal with them? Help me! =]
In general you only need to echo/log exceptions, that cannot be otherwise handled. This pretty much means, that if you put your entire application within try block, there's only one place where you need to put echoing/logging logic (i.e. the catch block associated with the outermost try block).
If on the other hand the exception can be handled without stopping the application (in your example this could be providing a default numeric value, instead of incorrect value), then there's usually no need to echo/log it.
If you do want to log such exceptions (for debugging for example), then your application should contain a logging framework, so that it's enough to do in your catch blocks something like
} catch (Exception $e) {
ExceptionLogger::log($e); //static method == ugly, but it's for simplicity in this example
// do whatever needs to be done
}
log() method above would check if the logging is enabled, and if it is savenecessary data to a file.
Exceptions should be typed based upon the error that you find. The Spl Exceptions are a good start, but you really should be creating your own exceptions as well. Some common ones that I use:
FileNotFoundException extends RuntimeException <- self explanatory
HTTPException extends RuntimeException <- Used for http classes when a non-200 result is encountered
DatabaseQueryException extends LogicException <- Used for database query errors
Now, by typing them specifically, it lets you handle the errors in your code. So let's say that you want to fetch a HTTP resource. If that fails with anything but a 404, you want to try a backup URL. You could do that with:
try {
return getHttp($url1):
} catch (HttpException $e) {
if ($e->getCode() != 404) {
try {
return getHttp($url2);
} catch (HttpException $e2) {
//It's ok to ignore this, since why know it's an HTTP error and not something worse
return false;
}
} else {
return false;
}
}
As far as your example code that you posted, I would change a few things:
Change the thrown exception to InvalidArgumentException since it has more semantic meaning (I almost never throw a raw exception).
You should try to avoid catch(Exception $e) at all costs. You have no idea what exception was thrown, so how can you possibly handle it?
Only catch exceptions that you are reasonably sure you know how to handle (and outputting an error/logging is not handling, it's removing the usefulness of the exception). You should never see something like catch($e) { logerror($e); } or catch($e) { print $e->getMessage(); } since netiher is actually handling the exception.
If you don't fix or workaround the cause of the exception in your catch block, you should re-throw it. Let the code above you in the stack try to handle it. This is especially true with libraries and classes that are reused all over the place.
Now, with user interfaces, it may be acceptable to catch the exception and show the user an error message. So your example where you print the exception's message might be ok, but you'd really need to think about the use-cases of it. Are you calling it from a model or controller? If so, it may be ok display an error message. Are you calling it from a library? If so, it's probably better to let the exception bubble up.
Also, don't use a global try{} catch() {} block. Instead, install an Exception Handler to handle it for you. It's cleaner, and more semantically correct (since any try{}catch{} implies that you know how to handle the exception that you caught, whereas the exception handler is precisely meant for exceptions that weren't handled because you didn't know how to handle them.
Exceptions are for exceptional circumstances. Do not use them for all error conditions. If a user submits a password that's too short, don't throw an exception, handle that in validation. But if your hash function is expecting sha256 to be available and it isn't, that's a time for an exception. Exceptions are useful for program errors (when a condition that is unexpected happens, such as invalid input to a function), state errors (when the application enters a state that is unknown or unstable, such as if the requested view does not exist) and runtime errors (when the application encounters an error that can only be detected at runtime, such as a file-not-found error).
There is an entire page of the PHP manual devoted to extending exceptions and that page also gives you a lot of information on the methods to identify file/line number, backtrace etc. where the exception was thrown. This is the type of information that is extremely useful for debugging.

Categories