Exceptions Handling In PHP
PHP 5 has an exception model similar to other programming languages. Exceptions are important and provide better control over error handling. The main purpose of using exception handling is to maintain the normal execution of the application.
Why Exception handling?
Exception Keywords
Exception Handling Methods
Method | Description |
---|---|
getMessage() : | Returns the message passed to the constructor |
getCode() : | Returns the error code passed to the constructor |
getLine() : | Returns the line number where the exception was thrown |
getFile() : | Returns the name of the file which has thrown the exception |
getTrace() : | Returns the array which consists the information like file name, line, function and its parameters |
getTraceAsString(): | Returns the information given by getTrace() in string format |
Example
try{ $FH=fopen("input.txt","r"); if(!$FH){ throw new Exception("no input file",1); } $SH=fopen("config.txt","r"); if(!$SH){ throw new Exception("no config file",2); } echo "File are opened successfully"; } catch (Exception $e){ echo "Error:".$e->getMessage()."
"; echo "Code:".$e->getCode()."
"; }