Difference between Error - Exception - Throwable within catch()

Asked

Viewed 666 times

-1

Always when I treated the catch I wore (Exception e) but a few days ago I came across an exception that did not fit the catch (Exception e) then I discovered that she is not really an exception but a mistake. Soon then I started sweating catch (Error | Exception e) but today I came across a code that uses only catch (Throwable e).

So I’d like to know the difference between those terms, or, I don’t know what to call them.

  • Enter in the topic of Specific use of Try-catch and I found nothing talking about Error, in the end I ended up finding other topics about which more or less solved my question, but honestly I don’t think my question is duplicate of this that you marked the doubts are quite different.

  • What programming language are you talking about? There is one more than one language that has Exception and Throwable, but the rules vary from one to the other.

  • I work with java, but I thought the rules of explanation were the same for most other languages.

  • From what I understood so much the Error as to Exception implement the interface Throwable so if I did one catch (Throwable e) I will capture all the playable objects that in this case are the exceptions and errors, entertaining if I catch (Exception e) I will capture all the flitable objects of the type Exception and if I do catch (Error e) I will capture all the flitable objects of the type Error. This right the logic?

  • In Java, Throwable is a class, not an interface. You got a response about PHP because you didn’t say what language you were talking about and a friend there thought it might be PHP. It also meant that your question was confused and poorly elaborated, and therefore closed (after all, it was unclear what language you were talking about). Now, knowing that her question was about Java, she may be a duplicate of this other question.

1 answer

1

Throwable is the base interface for any deployable object.

Source: PHP - Throwable

Exception is the base class for all Exceptions in the PHP 5, and the base class of all user exceptions in the PHP 7.

Source: PHP - Exception

In short, to capture the interface is equivalent to capturing all classes that implement it...

- I don’t know what to call them

Imagine the following scenario: you extends the class \Exception in your project and, when you want to stop something from running and simply display the message, launch that class. But in the event of a fatal error, literal exception, and so on, you display the error message and complete the execution of the script. Example:

<?php

try {
    bar();
    if (!baz())
        throw new MinhaExcecao('A função baz() retornou falso.');
} catch (MinhaExcecao $e) {
    echo $e -> getMessage();
    // O script vai continuar a ser executado...
} catch (PDOException $e) {
    die('PDO lançou uma exceção. Há algo errado na conexão/consulta do banco de dados.');
    // O script não vai continuar a ser executado...
} catch (Throwable $e) {
    die('Capturado alguma classe que implementa a interface Throwable');
    // O script não vai continuar a ser executado...
}

echo 'foo';

If the function baz() return false, will fall on the block catch (MinhaExcecao $e) with the echo and soon the script will continue on echo 'foo';... In other cases, the execution will be totally interrupted by the function call die().

It is worth remembering that the catch act as a cascade. When launching some object, it will be captured in the first block catch compatible with the launched class/interface. This way, your custom class should be captured first or before your parent class/interface, or else it won’t arrive at the catch intended.

There’s still the block Finally which, theoretically, ALWAYS runs.

Extend the class \Exception is very useful when you want to pass some error message to the user to which he did something wrong. The other messages are usually errors of the programmer or some feature that is not working properly. Hence it is better to generate a log accessible only to you (admin/dev). The user does not need to know why or where such errors occur. Logically it would be very useful to say something like: "This appeal made an error", but without detailing...

Another typical example is the connection to the database with PHP via PDO that explicitly displays the data when it is not in a block try / catch suitable:

Erro PDO/PHP

I used the PHP as a reference, but the theory is equivalent in the main programming languages. Perhaps there are some small differences...

  • From what I understand both Error and Exception extend Throwable is this? So if I put catch (Throwable and) I would capture any exception or error generated? On the question of the 'own' exceptions I had already studied a little about, but even so thank you help clarify even more.

  • Yes, but it would be right to say that they implement the Throwable interface. And, logically, you should capture each type of exception in its proper place...

  • Yes, I confused the word extend with implement, in most cases I work each exception separately but in some cases it is much better to capture everything at once. Thanks for the explanation.

Browser other questions tagged

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