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

Asked

Viewed 31,170 times

27

I’ve been looking for some explanations on the subject, but I couldn’t find one that was simple and straightforward. My question is : What Try/Catch Blocks are for and when they should be used?

  • I was going to answer but you already have an answer accepted, I think you don’t need more.

  • You can answer if you want, the better! hehe

5 answers

34


Block try/catch serves for handling exceptions, handling codes that may not be fully met and generate some exception/error.

The try can recover errors that may occur in the code provided in your block.
The catch in turn makes the handling of the mistakes that happened.

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 on what to run after try/catch (usually release resources). In case an exception is captured, the finally will be executed only after the completion of the instructions provided in catch. In case no exception is generated, the finally shall be executed after the instructions provided 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 block try/catch, can generate inconvenient messages to users who use their system. Let’s look at an example:

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

If the above code runs, it will generate a very beautiful error message on the screen

//Fatal error: Uncaught exception 'Exception' with message 'teste' in ...

14

Blocks of try/catch are blocks to treat exceptions that the programmer has no way to predict that will happen, runtime errors, that there is no way for the programmer to control, as for example, the user lose the connection to the internet. These unexpected behaviors are dealt with by the release of exceptions, these exceptions throw errors, warning that an unexpected behavior has happened.

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

In summary, the try/catch serves to treat behaviors unexpected, however it is much slower than managing the flow of a program with if/else, ie, should be used preferably when the developer there is no guarantee that that code will be executed successfully.

  • 1

    Thank you for the reply, very well summarised and explained.

  • The highlight in unexpected is a mistake, even for firing an exception using throw new Exception('meu erro') - which makes the unexpected in expected and controlled. (Unless you have misinterpreted your explanation...)

  • @Papacharlie, what I meant by unexpected is that even though I have the throw, this release should not occur and I will only "discover" it at runtime. So I used the example of connection loss. Since an expected error can be treated with program flows, such as a division by zero.

7

When to use

You will use this block when you use some method that launches a Checkedexception and when you want to give some treatment to Exception.

A "Try" block is called a "protected" block because, if a problem occurs with the commands inside the block, the execution will deviate to the corresponding "catch" blocks.

We need to use Try, because we are doing conversion operation, it is a more robust way to handle possible errors at the time of conversion, for example it is not possible to convert a character "?" by a number, however as the data entry is released the end user may enter something inappropriate resulting in error and break of the program execution by failure, with Try we can avoid this sudden drop 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 by the name of the type of exception. Blocks cannot 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 run. In general, it includes commands that release resources that may eventually have been allocated during Try block processing and that can be released, regardless of whether the execution has successfully terminated or has been interrupted by an exception condition. The presence of this block is optional.

Source : http://www.devmedia.com.br/blocos-try-catch/7339.

  • 2

    In php it has not checked exceptions, the problem is that not all Exception in php some functions return value to indicate failure.

6

The best way to understand the importance of using blocks try{} catch{} finally{} is to have total science of a truth in the world of programming:

  • There is no application that does not generate exceptions

And these exceptions can be generated in their forms: nonpurposeful and purposeful. Nonpurposeful exceptions are generated by the system in the form of bugs, i.e., unknown bugs in the application. The purposeful exceptions are generated by the systems for processing expected errors that can generate bugs untreated case, such as processing of parameter validations through the exception Invalidargumentsexception.

In this context why use exceptions? Creating an exception or anything else in the code needs something very important called NEED. A good example that explains what I mean is the unnecessary use of getters e setters as best practices. Since when create something in your application that no other class will use? 'Cause I’m gonna create a block of exceptions if I’m not gonna use it for anything?

In this sense I will expose 4 situations that use the block of exceptions in the applications that I currently create.

  1. Block of exceptions in Controller;
  2. Manipulation of the stack trace;
  3. Applying business rules when an exception occurs;
  4. Exception monitoring for logs.

Block of exceptions in the controller - The positive points I see when creating exceptions in controller:

  • Primary error view for the front-end: Imagine the following class hierarchy. Controller > Service_01 > Service_02 > Service_03. The business rule contained in this scenario is a bug (throw Exception) occurred in the class Service_03. If you do not have the requirements of items 2 to 4. The use of the exception block in Controller will be sufficient for all the rules contained in Services. The primary error will arrive without interference from other exception blocks and can be manipulated only at the end, at the time of display to the user. Of course a more user-friendly treatise should be performed for the user.

  • Negotiations for user-friendly exceptions: regarding this approach the construction of exception blocks in controller will allow to center the rule on a class of type abstrat extending to all the controller. In this scenario you will be applying concepts OOP state, abstraction, encapsulation, inheritance, dependency, etc. , concepts of SOLID, as the Principle of Sole Responsibility, that is, only the controller must carry out the negotiations of friendly exceptions.

Manipulation of the stack trace - Transform exceptions that do not serve for useful exception. For example, an error of ReflactionClass. I know the class BuutonEnum can generate exception Unhandled \ReflectionException (Reflectionexception untreated). And this can only occur if it is called out of context. So in catch{} mani as the exception must be generated to get to the Controller.

abstract class ButtonEnum
{

    public static function all($class)
    {
        try {
            $reflector = new ReflectionClass($class);
        } catch (\ReflectionException $e) {
            throw new InvalidArgumentException('Class is not a button type');
        }
        return $reflector->getConstants();
    }
}

class ButtonType2Enum
{
    const DEFAULT = 'default';
    const PRIMARY = 'primary';
    const DANGER = 'danger';

    public static function all()
    {
        return ButtonEnum::all(__CLASS__);
    }
}

Applying business rules when an exception occurs Who ever?

    try {
        DB::beginTransaction();
        // do something
        DB::commit();
    } catch (\Exception $ex) {
        // do something
        DB::rollBack();
    }

The famous example of just persisting the code if all went well. A more complex case that I had the pleasure of working on was related to data curation. Data were only accepted by the system if a whole match validation of financial values of expenses and revenues were accepted.

Exception monitoring for logs: In extremely important features of an application, for example, the payment flow of any e-commerce page is, in my opinion, an important point for monitoring. Soon, what happens in this stream, the sooner the team gets to know will be better. Imagine now a team of over 30 people adding and removing code. So, tools like bugsnag and graylog are placed in catch{} for exceptions that need to be monitored.

6

To simplify, imagine that Voce is doing some operations, for example splitting.

var a  = b / c;

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

Errors of this type cannot be 'compared' in an IF. That’s why the use of TRY (try in English)

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");

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.