What are Try / Catch Blocks for and when should they be used?

18

I've been looking for some explanations on the subject, but I have not found any that are simple and straightforward. My question is: What are Try / Catch Blocks for when they should be used?

    
asked by anonymous 15.04.2015 / 15:18

4 answers

24

Block try/catch is used to handle exceptions, handling of codes that may not be fully met and generate some exception / error.

try can recover errors that may occur in the code provided in your block. catch in turn treats the errors that have occurred.

Example:

try {
    //Esse código precisa de tratamento pois pode gerar alguma exceção
    $x = 1;
    if ($x === 1)
        throw new \Exception('X não pode ser 1');
} catch (\Exception $e) {
    var_dump($e->getMessage());
}

In addition we also have a block called finally (PHP 5.5 or higher), which provide instructions of what should be executed after try/catch (usually resource release). If an exception is caught, finally will be executed only after the completion of the instructions given in catch . If no exceptions are generated, finally will be executed after the instructions given in try .

Example:

try {
    //Esse código precisa de tratamento pois pode gerar alguma exceção
    $variavel = AlgumaCoisa::pegarRecurso();
    if ($variavel->executarAlgumaCoisa())
        throw new \Exception('Erro: ' . $variavel->pegarErro());
} catch (\Exception $e) {
    var_dump($e->getMessage());
} finally {
    $variavel->liberarRecurso(); 
}

Finally, errors generated outside a try/catch block can generate inconvenient messages to users using your system. Let's take an example:

//Nada antes
throw new Exception('teste');
//Nada depois

If the above code is executed, it will generate a very nice error message on the screen

//Fatal error: Uncaught exception 'Exception' with message 'teste' in ...
    
15.04.2015 / 15:43
10

Blocks of try/catch are blocks to handle exceptions that the programmer can not predict will happen, run-time errors, that there is no way for the programmer to control, such as losing the internet connection . These unexpected behaviors are handled with the Exceptions posting, these exceptions issue errors, warning you that unexpected behavior happened.

The try/catch block will treat this "critical" part of code and try to execute it, if no error occurs, the program follows its normal flow, otherwise it will enter the block that is within catch to treat the error.

In summary, try/catch is used to handle unexpected behaviors , however it is much slower than controlling the flow of a program with if/else , ie it should be used preferentially when developer can not guarantee that that code will run successfully.

    
15.04.2015 / 15:29
5

When to use

You will use this block when you use some method that throws a CheckedException and when you want to give some exception handling.

A "try" block is called a "protected" block because, in case of a problem with the commands within the block, execution will be diverted to the corresponding "catch" blocks.

We need to use try, because we are doing conversion operation, it is a more robust way of handling possible errors at the time of conversion, for example, it is not possible to convert a "?" character by a number, but as the data entry is released the end user may enter something inappropriate, resulting in error and breakdown of the program execution by failure, with try we can avoid this sudden crash and then treat the error in the best way.

Syntax

The structuring of these blocks follows the following syntax:

try {

// código que inclui comandos/invocações de métodos

// que podem gerar uma situação de exceção.

}

catch (XException ex) {

// bloco de tratamento associado à condição de

// exceção XException ou a qualquer uma de suas

// subclasses, identificada aqui pelo objeto

// com referência ex

}

catch (YException ey) {

// bloco de tratamento para a situação de exceção

// YException ou a qualquer uma de suas subclasses

}

finally {

// bloco de código que sempre será executado após

// o bloco try, independentemente de sua conclusão

// ter ocorrido normalmente ou ter sido interrompida

}

Where XException and YException should be replaced with the name of the exception type. Blocks can not be separated by other commands - a syntax error would be detected by the Java compiler in this case. Each try block can be followed by zero or more catch blocks, where each catch block refers to a single exception.

The finally block, when present, is always executed. In general, it includes commands that release resources that may have been allocated during the try block processing and can be released, regardless of whether the execution has ended successfully or been interrupted by an exception condition. The presence of this block is optional.

Source: link .

    
15.04.2015 / 15:30
4

For simplicity, imagine that you are doing some operations, for example division.

var a  = b / c;

What happens if C assumes the value of 0? The program will show a division error by 0.

Errors of this type can not be 'compared' in an IF. For this reason the use of TRY

TRY{ ///TENTE FAZER AS PROXIMAS OPERACOES
 ...operacoes
 }CATCH{ /// se houver algum erro/exception em '...operacoes' 
 ... o que fazer
 }

In this case:

try {
    double a=10;
    double b=0;
    double result=a/b; 
    System.out.println(result);
    System.out.println("inside-try");
} catch (Exception e) {

    System.out.println("division by zero exception");
    System.out.println("inside-catch");

}
    
15.04.2015 / 15:38