php?抛异常
Jun 20, 2016 pm 12:46 PM php如何自定义异常类,捕获异常和抛出异常.
或者给个例子参考下
回复讨论(解决方案)
try { throw new Exception($error); } catch (Exception $e) { echo $e->getMessage(); }
try{
throw new Exception($error);
}catch(Exception $e){
echo $e->getCode();
}
set_exception_handler('myException');test(-1);function test($a){ if($a < 0){ throw new Exception('error'); } return $a;}function myException($e){ $msg='code : '.$e->getCode().'<br>message : '.$e->getMessage(); echo $msg;}
http://www.php.net/manual/zh/language.exceptions.php
function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } return 1/$x;}try { echo inverse(5) . "\n"; echo inverse(0) . "\n";} catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n";}// Continue executionecho "Hello World\n";以上例程会输出:0.2Caught exception: Division by zero.Hello World
自定义一个异常类
<?phpclass MyException extends Exception { }class Test { public function testing() { try { try { throw new MyException('foo!'); } catch (MyException $e) { // rethrow it throw $e; } } catch (Exception $e) { var_dump($e->getMessage()); } }}$foo = new Test;$foo->testing();?>
try {
throw new Exception($error);
} catch (Exception $e) {
echo $e->getMessage();
}
楼上都是正解

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
