ADVERTISEMENT
ADVERTISEMENT

PHP program to demonstrate the use of multiple catch blocks

Here, we are going to demonstrate the use of multiple catch blocks in PHP.
Submitted by Nidhi, on November 22, 2020

Here, we will demonstrate the multiple catch blocks, here we will create a user define exception class and also used a predefined exception class.

Program/Source Code:

The source code to demonstrate the use of multiple catch blocks is given below. The given program is compiled and executed successfully.

<?php
// PHP program to demonstrate the use of multiple catch blocks.
class MyException extends Exception
{
}

try
{

    $A = 10;
    $B = - 1;

    if ($B == 0) throw new MyException("Divide by Zero exception");
    if ($B == - 1) throw new Exception("Negative exception");
    $C = $A / $B;
    printf("Value of C: %d<br>", $C);

}
catch(MyException $e)
{
    printf("Exception: %s<br>", $e->getMessage());
}
catch(Exception $e)
{
    printf("Exception: %s<br>", $e->getMessage());
}

?>

Output:

Exception: Negative exception

Explanation:

Here, we created a user-defined exception class that inherits the Exception class. In the try block, we have thrown exception based on the conditions for divide by zero and negative value exception, and we defined two catch blocks for the different exceptions.

The above program will throw an exception for the negative value that will be caught by the appropriate catch block and print an appropriate message on the webpage.

PHP Exception Handling Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.