Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 10 / 68

Error Handling (try...catch)

In this lesson you will learn error handling in PHP with try...catch, so an unexpected failure does not bring your whole program down. This is for anyone searching for "PHP try catch how to use".

throw raises an exception and try / catch catches it. It works like insurance: you decide in advance what to do if something goes wrong. It is an essential skill for coping with mistyped input and unpredictable trouble.

The sample code raises an exception with throw new Exception(...) inside divide when the divisor is zero. It calls that function inside a try block and prints the message from catch (Exception $e) using $e->getMessage().

A common stumbling block for beginners is getting the type in the catch wrong. To catch only one kind of failure you have to name the class, as in catch (ValidationError $e); leaving it as Exception swallows every exception at once.

Splitting your catch blocks by exception type lets you write a response tailored to each cause. Real web applications frequently separate database errors from input errors.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)