Welcome to FindNerd. We are going to discuss the finally block in php. We use it with Exception handling. Are you familiar with exception if not then check our
exception based blog Exception concept for help. finally block run always whenever code execute.
it will call after the try and catch blocks. Please have a look.
<?php
try{
throw new Exception('Run time issue');
} catch(Exception $e){
echo 'Runtime error' . \n;
}
finally{
echo 'finally block run';
}
?>
result: Runtime errror
finally block run
In above example we can see try and catch blocks called before the finally block. You can also extend the Exception class in your custom class and use it as Exception
class. Please have a look.
<?php
class MyCustom extends Exception
{
}
try
{
throw new MyCustom('Learning Exception');
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
result: Learning Exception
0 Comment(s)