[go: up one dir, main page]

Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST

PHP Tutorial

PHP HOME PHP Intro PHP Install PHP Syntax PHP Comments PHP Variables PHP Echo / Print PHP Data Types PHP Strings PHP Numbers PHP Casting PHP Math PHP Constants PHP Magic Constants PHP Operators PHP If...Else...Elseif PHP Switch PHP Loops PHP Functions PHP Arrays PHP Superglobals PHP RegEx PHP RegEx Functions

PHP Forms

PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete

PHP Advanced

PHP Date and Time PHP Include PHP File Handling PHP File Open/Read PHP File Create/Write PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions

PHP OOP

PHP What is OOP PHP Classes/Objects PHP Constructor PHP Destructor PHP Access Modifiers PHP Inheritance PHP Constants PHP Abstract Classes PHP Interfaces PHP Traits PHP Static Methods PHP Static Properties PHP Namespaces PHP Iterables

MySQL Database

MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data

PHP XML

PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat PHP XML DOM

PHP - AJAX

AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll

PHP Examples

PHP Examples PHP Compiler PHP Quiz PHP Exercises PHP Server PHP Syllabus PHP Study Plan PHP Certificate

PHP Reference

PHP Overview PHP Array PHP Calendar PHP Date PHP Directory PHP Error PHP Exception PHP Filesystem PHP Filter PHP FTP PHP JSON PHP Keywords PHP Libxml PHP Mail PHP Math PHP Misc PHP MySQLi PHP Network PHP Output Control PHP RegEx PHP SimpleXML PHP Stream PHP String PHP Variable Handling PHP XML Parser PHP Zip PHP Timezones

PHP Exceptions


What is PHP Exceptions?

An exception is an unwanted or unexpected event that occurs during the execution of a PHP script.

Exceptions are thrown by many PHP functions and classes (if an unexpected situation arises, such as invalid data). When an exception is thrown, it can be caught by a block of code (usually a try...catch block) with proper error handling. If an exception is not caught, it will be handled by the default exception handler and often results in a fatal error and script termination.

PHP uses the following keywords for exception handling:

  • throw - This keyword is used to throw exceptions.
  • try - This keyword is used to create a try...catch, or a try...catch...finally statement.
  • catch - This keyword is used to handle exceptions that are thrown by the code in a preceding try block.
  • finally - This keyword is used in try...finally and try...catch...finally to run a block of code whether or not an exception occurred.

PHP throw Keyword

The throw keyword is used to throw an exception.

If an exception is NOT caught, a fatal error will occur with an "Uncaught Exception" message, and the script is terminated.

Here we throw an exception without catching it:

Example

<?php
function divide($x, $y) {
  if($y == 0) {
    throw new Exception("Cannot divide by zero.");
  }
  return $x / $y;
}

echo divide(5, 0); // code that can throw an exception
echo 'Hello';
?>
Try it Yourself »

The result will look something like this:

Fatal error: Uncaught Exception: Division by zero in C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4

PHP try...catch Keyword

Here we use the try...catch keyword, to catch the exception/error from the example above and continue the script.

Syntax

try {
  code that can throw an exception
} catch(Exception $e) { code to run when an exception is caught
}

Example

Display a message when an exception is thrown, and continue script:

<?php
function divide($x, $y) {
  if($y == 0) {
    throw new Exception("Cannot divide by zero.");
  }
  return $x / $y;
}

try {
  echo divide(5, 0);  // can throw an exception
} catch(Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

echo '<br>Hello';
?>
Try it Yourself »

The catch block indicates what type of exception should be caught and the name of the variable which can be used to access the exception. In the example above, the type of exception is Exception and the variable name is $e.



PHP try...catch...finally Keyword

The try...catch...finally keyword can be used to catch exceptions.

The code in the finally block will run regardless of whether an exception was caught.

Syntax

try {
  code that can throw an exception
} catch(Exception $e) { code to run when an exception is caught
} finally {
  code that always runs regardless of exception
}

Example

Display a message when an exception is thrown, and then indicate that the process is complete:

<?php
function divide($x, $y) {
  if($y == 0) {
    throw new Exception("Cannot divide by zero.");
  }
  return $x / $y;
}

try {
  echo divide(5, 0); // can throw an exception
} catch(Exception $e) {
  echo 'Error: ' . $e->getMessage();
} finally {
  echo '<br>Process complete.';
}
?>
Try it Yourself »

PHP Exception Object

The Exception Object contains information about the unexpected behaviour the function encountered.

Syntax

new Exception(message, code, previous)

Parameter Values

Parameter Description
message Optional. A string describing why the exception was thrown
code Optional. An integer that can be used to easily distinguish this exception from others of the same type
previous Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter

Methods

When catching an exception, the following table shows some of the methods that can be used to get information about the exception:

Method Description
getMessage() Returns a string describing why the exception was thrown
getPrevious() If the exception was triggered by another one, this method returns the previous exception
getCode() Returns an integer which can be used to identify the exception
getFile() Returns the absolute path to the file where the exception occured
getLine() Returns the line number of the code that threw the exception

The following example uses several of the Exception methods to get more information about the exception that was thrown:

Example

Output more information about the exception that was thrown:

<?php
function divide($x, $y) {
  if($y == 0) {
    throw new Exception("Cannot divide by zero.");
  }
  return $x / $y;
}

try {
  echo divide(5, 0);
} catch(Exception $e) {
  $file = $e->getFile();
  $line = $e->getLine();
  $code = $e->getCode();
  $message = $e->getMessage();
  echo "Exception thrown in $file on line $line: [Code $code] $message";
}
?>
Try it Yourself »

Complete Exception Reference

For a complete reference, go to our Complete PHP Exception Reference.

The reference contains descriptions and examples of all Exception methods.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->