PHP Exception Handling vs C #

This is really a basic question (hopefully). Most of the exception handling I did was with C #. In C #, any code that contains errors in a catch try block is handled by catch code. for instance

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

The error will be displayed in errorCode.text. If I tried to run the same code in php:

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

The catch code does not run. Based on my limited understanding, php needs a throw. Doesn't that defeat the whole purpose of error checking? Doesn't that reduce the catch attempt to an if then statement? if (division by zero) throw error Please tell me that I do not need to anticipate every possible error in an attempt to catch a throw. If so, does it still make php error handling behave like C #?

+3
4

php- set_error_handler() ErrorException :

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();
}
+6

PHP try-catch , .

, .

:

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();
}
+2

, PHP - :

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

Unlike C #, not every problem throws an exception in PHP. Some problems are silently ignored (or not silent - they print something at the output), but there are other ways to fix them. I believe this is because exceptions have not been part of the language since the first version, so there are some "obsolete" mechanisms.

+1
source

Source: https://habr.com/ru/post/1771403/


All Articles