Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. try / catch / finally / throw

try / catch / finally / throw Since: PHP 5(2004)

Exception handling is a mechanism for catching errors that occur during program execution and responding to them appropriately. It is used in operations that may fail at runtime, such as database access and file I/O.

Syntax

// Basic syntax for catching exceptions.
try {
	// Code that may throw an exception
} catch (Exception $e) {
	// Code to handle the exception
} finally {
	// Code that always runs, regardless of whether an exception occurred
}

// Throws an exception.
throw new Exception($message, $code);

Syntax Overview

SyntaxDescription
tryA block that wraps code which may throw an exception.
catch (ExceptionType $e)Catches an exception of the specified type. You can chain multiple catch blocks to handle different exception types individually.
finallyA block that always executes regardless of whether an exception was thrown. Available in PHP 5.5 and later.
throwThrows an exception object. Execution is interrupted and control transfers to the nearest matching catch block.

Common Exception Classes

ClassDescription
ExceptionThe base class for all exceptions.
RuntimeExceptionRepresents exceptions that occur during runtime.
InvalidArgumentExceptionThrown when an invalid argument is passed.
PDOExceptionThrown when a database operation fails.
TypeErrorThrown when a type mismatch occurs. Available in PHP 7 and later.
ValueErrorThrown when a value is invalid despite having the correct type. Available in PHP 8 and later.
JsonExceptionThrown when a JSON conversion error occurs. Available in PHP 7.3 and later.

Sample Code

<?php
// Basic exception handling.
try {
	$result = 10 / 0; // Triggers a division by zero error.
} catch (DivisionByZeroError $e) {
	echo "Error: " . $e->getMessage(); // Outputs "Division by zero".
}

// Throwing and catching an exception.
function validateAge(int $age): void
{
	if ($age < 0 || $age > 150) {
		throw new InvalidArgumentException("Age must be between 0 and 150.");
	}
}

try {
	validateAge(200);
} catch (InvalidArgumentException $e) {
	echo $e->getMessage(); // Outputs "Age must be between 0 and 150."
}

// Handling multiple exception types individually.
try {
	$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'password');
	$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
	$stmt->execute([':id' => 'abc']); // Invalid value
} catch (PDOException $e) {
	echo "Database error: " . $e->getMessage();
} catch (Exception $e) {
	echo "Unexpected error: " . $e->getMessage();
}

// In PHP 8+, you can catch multiple types using a pipe (|).
try {
	$data = json_decode('invalid', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException | InvalidArgumentException $e) {
	echo "Input data error: " . $e->getMessage();
}

// The finally block always runs.
$file = null;
try {
	$file = fopen('data.txt', 'r');
	if ($file === false) {
		throw new RuntimeException("Could not open the file.");
	}
	$content = fread($file, filesize('data.txt'));
	echo $content;
} catch (RuntimeException $e) {
	echo "Error: " . $e->getMessage();
} finally {
	if ($file !== null) {
		fclose($file); // Ensures the file is closed even if an exception occurs.
	}
}

// Common methods of Exception.
try {
	throw new Exception("Test error", 500);
} catch (Exception $e) {
	echo $e->getMessage(); // Outputs "Test error".
	echo $e->getCode(); // Outputs "500".
	echo $e->getFile(); // Outputs the filename where the exception was thrown.
	echo $e->getLine(); // Outputs the line number where the exception was thrown.
}

// Defining a custom exception class.
class AppException extends RuntimeException
{
	private string $detail;

	public function __construct(string $message, string $detail, int $code = 0)
	{
		parent::__construct($message, $code);
		$this->detail = $detail;
	}

	public function getDetail(): string
	{
		return $this->detail;
	}
}

try {
	throw new AppException("Authentication error", "The token has expired.", 401);
} catch (AppException $e) {
	echo $e->getMessage() . ": " . $e->getDetail();
}

Notes

try / catch is PHP's exception handling syntax, used to safely handle runtime errors. Always wrap operations that may fail — such as database access, file I/O, and external API calls — in exception handling blocks. If an exception is not caught, the script terminates and an error message is displayed to the user.

In catch blocks, specifying a concrete exception type allows you to handle different kinds of errors appropriately. If you write a broad type like Exception first, subsequent catch blocks will never be reached — so always order your catch blocks from most specific to most general.

The finally block always executes regardless of whether an exception occurred, making it ideal for releasing resources. When combining exception handling with database transactions, see beginTransaction() / commit() / rollBack(). For JSON conversion error handling, see json_encode() / json_decode().

If you find any errors or copyright issues, please .