Doubts about the try-catch in php

-1

Good afternoon and thanks in advance for losing a few minutes of your time solving my doubts. there goes my question: Are the exceptions in PHP launched automatically as for example in java or should they be launched manually? Greetings

    
asked by Alberto Alaber 15.01.2018 в 18:25
source

1 answer

0

PHP is already able to throw more common errors, for example a division by zero, or that can not make a query, etc ...

In case you want to do it, for example you can check (if) if the two parameters are numbers you can do it in the following way.

<?php 

    function comprobar($num1,$num2){

            if(is_numeric($num1) && is_numeric($num2)){
                echo "Son numeros";
            }else{
                throw new Exception("Error, los dos parametros tienen que ser numeros", 1);
            }

    }
    try {
        comprobar("asd",1);

    } catch (Exception $e) {
        //Captamos la excepción si existe.
        echo $e->getMessage();
    }

 ?>

That is to say, the verifications you have to do, and if necessary, raise an exception.

You can also add a finally block, which means in any case do this. Example: If you have a connection to a database, the ideal would be to close the connection at the end of everything, using the finally block.

As A.Cedano said, it is better to read the PHP manual, which is very well explained.

I hope I have helped you.

    
answered by 15.01.2018 в 19:35