Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Exceptions in PHP

Exceptions in PHP

? Exceptions in PHP

Exceptions are a way to handle errors gracefully in PHP. Instead of letting a program crash when something goes wrong, you can "catch" the error and handle it in a controlled manner.


? Basic Syntax of Exception Handling

try {    // Code that may throw an exception    throw new Exception("This is an error!");} catch (Exception $e) {    // Code that handles the exception    echo "Caught exception: " . $e->getMessage();}

? Key Terms

  • try: Block of code that might throw an exception.

  • throw: Used to manually throw an exception.

  • catch: Catches the exception and allows you to handle it.


? Example: Division by Zero

<?phpfunction divide($a, $b) {    if ($b == 0) {        throw new Exception("Division by zero not allowed.");    }    return $a / $b;}try {    echo divide(10, 0);} catch (Exception $e) {    echo "Error: " . $e->getMessage();}?>

Output:

Error: Division by zero not allowed.

? Custom Exception Class

You can create your own exception class:

<?phpclass MyException extends Exception {    public function errorMessage() {        return "Custom Error: " . $this->getMessage();    }}try {    throw new MyException("Something went wrong.");} catch (MyException $e) {    echo $e->errorMessage();}?>

? Using finally Block

The finally block always executes, whether or not an exception was thrown.

<?phptry {    echo "Trying...<br>";    throw new Exception("Oops!");} catch (Exception $e) {    echo "Caught: " . $e->getMessage() . "<br>";} finally {    echo "Always executes this block.";}?>

? Exception Methods

MethodDescription
$e->getMessage()Returns the error message
$e->getCode()Returns the error code
$e->getFile()Returns the file where the error occurred
$e->getLine()Returns the line number
$e->getTrace()Returns an array of the backtrace
$e->getTraceAsString()Returns the backtrace as a string

? Practical Use Case: File Opening

<?phptry {    $file = @fopen("nonexistent.txt", "r");    if (!$file) {        throw new Exception("File not found.");    }} catch (Exception $e) {    echo "Error: " . $e->getMessage();}?>

? Tips

  • Only use exceptions for exceptional situations.

  • Do not suppress all errors—log them for debugging.

  • Combine exception handling with validation for robust code.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql