![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Exception Handling in PHP ?
An exception is a problem that arised during the execution of a program. During the execution of a program when an exception occurs, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception”.
Syntax
try { print "this is our try block"; throw new Exception(); }catch (Exception $e) { print "something went wrong, caught yah! n"; }finally { print "this part is always executed"; }
Example
<?php function printdata($data) { try { //If var is six then only if will be executed if($data == 6) { // If var is zero then only exception is thrown throw new Exception('Number is six.'); echo "
After throw (It will never be executed)"; } } // When Exception has been thrown by try block catch(Exception $e){ echo "
Exception Caught", $e->getMessage(); } //this block code will always executed. finally{ echo "
Final block will be always executed"; } } // Exception will not be rised here printdata(0); // Exception will be rised printdata(6); ?>
Output
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
Note
To handle exceptions, program code must inside a try block. Each try must have at least one respective catch block. Multiple catch blocks can be used to catch different classes of exceptions.
Advertisements