1function inverso($x) {
2 if (!$x) {
3 throw new Exception('Zero division.');
4 }
5 return 1/$x;
6}
7
8try {
9 echo inverso(5) . "\n";
10 echo inverso(0) . "\n";
11} catch (Exception $e) {
12 echo 'and the error is: ', $e->getMessage(), "\n";
13}
1
2<?php
3
4function test() {
5 try {
6 throw new Exception('foo');
7 } catch (Exception $e) {
8 return 'catch';
9 } finally {
10 return 'finally';
11 }
12}
13
14echo test();
15?>
16
17
1
2<?php
3function inverse($x) {
4 if (!$x) {
5 throw new Exception('Division durch Null.');
6 }
7 return 1/$x;
8}
9
10try {
11 echo inverse(5) . "\n";
12 echo inverse(0) . "\n";
13} catch (Exception $e) {
14 echo 'Exception abgefangen: ', $e->getMessage(), "\n";
15}
16
17// Ausführung fortsetzen
18echo "Hallo Welt\n";
19?>
20
21
1Try catch comes under exception handeling concept where using this we control the runtime error and modify the message as we want.
2
3// function created with exception throw
4function checkdata($number){
5 if($number > 10){
6 throw new Exception("Number is greater than 10");
7 }
8 return true;
9}
10
11// try block starts
12try{
13 checkdata(15);
14 echo "The number is below 10";
15}
16// catch block
17catch(Exception $e){
18 echo "Message :".$e->getMessage();
19}
20
21In above code if condition is not satisfied then it will throw exception and which gets caught by catch block and show the error message.
1try
2{
3 // Some code...
4}
5catch(AError | BError $e)
6{
7 // Handle exceptions
8}
9catch(Exception $e)
10{
11 // Handle the general case
12}