PHP exception Handling vs C#

2019-04-11 05:34发布

问题:

this is a really basic question (I hope). Most of the exception handling I have done has been with c#. In c# any code that errors out in a try catch block is dealt with by the catch code. For example

try
{
 int divByZero=45/0;
}
catch(Exception ex)
{
 errorCode.text=ex.message();
}

The error would be displayed in errorCode.text. If I were to try and run the same code in php however:

try{
    $divByZero=45/0;
    }
catch(Exception ex)
{
  echo ex->getMessage();
}

The catch code is not run. Based on my limeted understanding, php needs a throw. Doesn't that defeat the entire purpose of error checking? Doesn't this reduce a try catch to an if then statement? if(dividing by zero)throw error Please tell me that I don't have to anticipate every possible error in a try catch with a throw. If I do, is there anyway to make php's error handling behave more like c#?

回答1:

You could also convert all your php errors with set_error_handler() and ErrorException into exceptions:

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

try {
    $a = 1 / 0;
} catch (ErrorException $e) {
    echo $e->getMessage();
}


回答2:

PHP's try-catch was implemented later in the language's life, and so it only applies to user-defined exceptions.

If you really want to handle actual errors, set your own error handler.

To define and catch exceptions:

function oops($a)
{
    if (!$a) {
        throw new Exception('empty variable');
    }
    return "oops, $a";
}

try {
    print oops($b);
} catch (Exception $e) {
    print "Error occurred: " . $e->getMessage();
}


回答3:

From http://php.net/manual/en/language.exceptions.php

"Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException."

See also http://www.php.net/manual/en/class.errorexception.php



回答4:

I think the only way to deal with this in PHP is to write:

try
{ 
  if ($b == 0) throw new Exception('Division by zero.');
  $divByZero = $a / $b; 
} 
catch(Exception ex) 
{ 
  echo ex->getMessage(); 
} 

Unlike in C#, not every issue will raise an exception in PHP. Some issues are silently ignored (or not silently - they print something to the output), but there are other ways to handle these. I suppose this is because exceptions were not a part of the language since the first version, so there are some "legacy" mechanisms.