What is exception handling in PHP

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block.

We will show different error handling methods:

Basic use of ExceptionsCreating a custom exception handlerMultiple exceptionsRe-throwing an exceptionSetting a top level exception handler

Principles of exceptions

Code may be surrounded in a try block, to help catch potential exceptionsEach try block or “throw” must have at least one corresponding catch blockMultiple catch blocks can be used to catch different classes of exceptionsExceptions can be thrown (or re-thrown) in a catch block within a try block

The basic syntax

1

2

3

4

5

6

7

8

try

{

// do something that can go wrong

}

catch(Exception$e)

{

thrownewException('Something really gone wrong',0,$e);

}

Complete Example of php exception handling

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

//create function with an exception

functioncheckNum($number)

{

if($number>1)

{

thrownewException(â€œValue must be1orbelow);

}

returntrue;

}

//trigger exception in a array block

try

{

checkNum(2);

//If the exception is thrown, this text will not be shown

echoIfyou see this,the number is1orbelow;

}

//catch exception

catch(Exception$e)

{

echo"Message: ".$e->getMessage();

}

?>

I hope this will help you. If you like this article, do like & share it with your friends on social media. Don’t forget to follow us on Facebook and Twitter to learn cool tutorials.

About: Prem Tiwari

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari