So in my code below, I'm not sure where i went wrong. Improper use of syntax, wrong use of variables? Please help!
For some reason i run this in the browser and get back
"Fatal error: Uncaught exception 'numexception' with message 'The numbers are not set' in C:\xampp\htdocs\php_testing\test.php:29 Stack trace: #0 {main} thrown in C:\xampp\htdocs\php_testing\test.php on line 29".
I don't understand where my code went wrong???
class numexception extends Exception{}
function multiply($a,$b){
echo $a*$b;
}
$var1 = 5;
//$var2 = 2; as you can see variable 2 is not set as I commented it out to test
//the exception
if(!isset($var1) or !isset($var2)){
throw new numexception("The numbers are not set");
}
try{
multiply($var1,$var2);
}
catch(numexception $e){
echo "This exception was caught:".$e->getMessage();
}
echo "The script then continues";
The throw is not in the try, so it can't be catched.
What your code is doing is like hitting someone with a golf ball, and then yelling "Fore!".
Related
I want to check if accessing mysql is possible or not.
I don't wont to have an error message, only true/false if the connection is ready or not.
I tried to do it with this :
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
But always a error message will come up - how can i prevent this message from showing ?
"<b>Fatal error</b>: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user ''
#'localhost' (using password: NO)' in /is/htdocs/...mypath
.php:33
Stack trace:
#0 /is/htdocs...mypath.myfile.php(33): mysqli->mysqli('', ''
, '', '')
#1 {main}
thrown in <b>/is/htdocs/wp1076647_373QG1K1B0/butobo/module/4/code/cms_checkcon.php</b> on line <b>33
</b><br />"
You need to "catch" this fatal exception via a try/catch statement. This allows you to handle the fatal error and then instead of your script crashing due to it, you can output an error message and exit instead :D
PHP Exceptions: http://php.net/manual/en/language.exceptions.php
I hope this helps.
try
{
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
exit;
}
This will change the ERROR to a WARNING, which will not break your script. From there, if you want to hide everything EXCEPT fatal errors, you can use this line of PHP:
error_reporting(E_ERROR);
Error message would display because your PHP is configured to do so. To make it not display, simply configure it like
ini_set('display_errors', "0");
However, this code also stops the execution. It order to prevent it, you have to catch the exception. So it should be like
try {
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
$res['code']=TRUE;
}
catch (Exception $e)
{
error_log($e);
$res['code']=FALSE;
}
while setting error_reporting(E_ERROR); is rather stupid as it will prevent you from seeing all other errors
When i initiate a class which does not exist , It throws the error, I Don't want to halted by that error . So i try trycatch method , But it still giving me same error, Can someone explain why this error is not been catched
I tried
try{$obj = new classname();}
catch(Exception $e){ echo 'class does not exist, move on' ;}
Fatal error: Class 'classname' not found in C:\WampDeveloper\Websites\localhost\webroot\index.php on line 4
Can someone explain why this error can not be catched ?
Is their is another way to catch and handle this kind of errors ?
UPDATE
We can catch mysql fatal errors by try catch method , So don't say fatal errors can not be handeled by try catch method
Two ways to solve this, use a autoloader that runs a custom written function for each object that does not exist so you can try to "include" a file on demand.
function autoload($objname){
if(is_readable(($f = '/path/to/class/'.$objname.'.php'))){
include $f;
} else {
throw Exception("$f does not exist");
}
}
spl_autoload_register('autoload');
new classname(); // try to load /path/to/class/classname.php
Or you can upgrade to PHP 7 where the error logic has had little overhaul:
Hierarchy
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
So a code like this would work:
try{
$obj = new classname();
} catch(Error $er){
echo 'class does not exist, move on';
} catch(Exception $ex){
echo 'a custom exception has been thrown:' . $ex->getMessage();
} catch(Throwable $t){
// Obsolete code, as Throwables are either Error or Exception, that were caught above.
}
I'm currently having a really frustrating time with some really simple SOAP / PHP at the moment. I've spent about a week trying EVERYTHING I can think of, on multiple different servers with different versions of PHP and they all still throw the same error. Here's the code:
function test() {
$client = new SoapClient('http://xxx', array("login" => "sandbox", "password" => "password"));
print_r($client->__getFunctions());
$ap_param = array();
// it dies here. CheckServiceAvailable is a valid function returned in __getFunctions()
$result = $client->__soapcall('CheckServiceAvailable', $ap_param);
if (is_soap_fault($result)) {
trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
}
It faults before the error catching can capture anything. Apache logs show the same fault as below:
Fatal error: Uncaught SoapFault exception: [s:Processing error] in C:\soap.php:13 Stack trace: #0 C:\soap.php(13): SoapClient->__soapCall('CheckServiceAva...', Array) #1 C:\soap.php(23): test() #2 {main} thrown in C:\soap.php on line 13
Without being able to catch the fault I'm totally stuck as to what to do. I don't really want to try nusoap.
Any ideas?
use:
try
{
$result = $client->__soapcall('CheckServiceAvailable', $ap_param);
}
catch (SoapFault $e)
{
echo "Cannot call method CheckServiceAvailable: {$e->getMessage()}";
}
I was trying out PHP exceptions for my project. But it turns out that the exception is thrown successfully but not being caught successfully by the code I wrote.
The code:
try{
require_once(MASTER_PHP."/master_validation.php");
require_once(MASTER_PHP."/master_user.php");
require_once(MASTER_PHP."/master_db.php"); require_once(MASTER_PHP."/master_secure.php");
require_once(MASTER_PHP."/master_ui.php");
require_once(MASTER_PHP."/master_mail.php");
require_once(MASTER_PHP."/master_filehandling.php");
require_once(MASTER_PHP."/master_archive.php");
require_once(MASTER_PHP."/master_date.php");
require_once(MASTER_PHP."/master_social.php");
require_once(MASTER_PHP."/master_message.php");
require_once(MASTER_PHP."/master_gallery.php");
require_once(MASTER_PHP."/master_backup.php");
require_once(MASTER_PHP."/master_payment.php");
require_once(MASTER_PHP."/master_sms.php");
require_once(MASTER_PHP."/master_xml.php");
$filterobj=new ta_filtervalue();
$filterobj->filterrequest();
global $noecho;
if($noecho!="yes")
{
$utilityobj=new ta_utilitymaster();
$utilityobj->includeextassets();
}
}
catch (Exception $e)
{
$custerrcode=$e->getMessage();
$dbobj=new ta_dboperations();
$res=$dbobj->dbquery("SELECT * FROM ".ERROR_CODES." WHERE ".errordb_errcode."='$custerrcode' LIMIT 0,1",DB_ERROR);
$errmsg=$res[0][changesqlquote(errordb_errdesc,"")];
$errpriority=$res[0][changesqlquote(errordb_errpriority,"")];
$errcallback1=$res[0][changesqlquote(errordb_errcallback1,"")];
$errcalltext1=$res[0][changesqlquote(errordb_errcallbacktext1,"")];
$errcallback2=$res[0][changesqlquote(errordb_errcallback2,"")];
$errcalltext2=$res[0][changesqlquote(errordb_errcallbacktext2,"")];
$errtitle=$res[0][changesqlquote(errordb_errtitle,"")];
$errobj=new ta_errorhandle();
$errobj->senderror($errmsg,$custerrcode,$errpriority,$errcallback1,$errcalltext1,$errcallback2,$errcalltext2,$errtitle);
}
If the exception occurs in master_user.php (required file) it has to be caught in the file which requires it. But it does not catch the exception.
The way I throw the exception:
throw new Exception('#ta#0000000_0000000');
where the string inside is the error code.
The error message:
Fatal error: Uncaught exception 'Exception' with message '#ta#0000000_0000000' in
C:\xampp\htdocs\techahoy\securedir\phpmaster\master_user.php:19 Stack trace: #0
C:\xampp\htdocs\techahoy\login\profile.php(4): ta_userinfo->userinit() #1 {main} thrown in
C:\xampp\htdocs\techahoy\securedir\phpmaster\master_user.php on line 19
Looks like (almost) the same as in here.
require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script
Fatal error: Uncaught exception
'EppCommandsExceptions' with message
'Required parameter missing'
The line in question:
throw new EppCommandsExceptions($result->msg, $codigo);
Why am I having this error on this line?
On EppCommandsExceptions.class.php
I have this class that extends Exception:
class EppCommandsExceptions extends Exception
{
//could be empty.
}
Next, on CommandsController.php I have:
include_once('EppCommandsExceptions.class.php');
and, later, if something bad happens on method1:
throw new EppCommandsExceptions($result->msg, $codigo);
later, on this same controller, another method2 that will run after method1,
I have:
if something goes bad with this too:
throw new EppCommandsExceptions($result->msg, $codigo);
Later I have, for the contact part - method1
try
{
$createdContact = $comandos->createContact($contactoVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
And later, for domain part: method2
try
{
$createdDomain = $comandos->createDomain($domainVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Domain. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Is it because I'm using the same exception for both methods?
Should I have one Exception class for EACH method? :s
Please advice,
Thanks a lot.
MEM
The exception you throw will only be caught if it's inside a try block.
If it isn't it'll propagate up the call stack, until it is caught in one of the earlier calling functions.
You're getting that fatal error because the exception you throw is never caught, so it's handled by the default unhandled exceptions handler, which emits the fatal error.
Examples:
try
{
$createdContact = $comandos->createContact($contactoVo);
if (error_condition())
throw new EppCommandsExceptions $e;
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Throwing the exception directly in the try block is not usually very useful, because you could just as well recover from the error condition directly instead of throwing an exception. This construct becomes more useful, though, if createContact may throw an exception. In this case, you have at some point to catch EppCommandsExceptions to avoid a fatal error.