Why do I have to use Try - catch?


There is a Java program in which, for example, there is a function displaying a list of categories, which is taken from the database via a mysql query. There is a separate function connecting to this database that is used in all functions-called Podkliucenije ();

Question: Why do I need to use try-catch in the functions themselves where there is already a call to the connection function and why does it give a bunch of errors without it, and with it everything does it work?

Connection function

Statement stmt;
Connection conn;

public void Podkliucenije()
    {
        // Podkliucenije k baze dannix
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            String DB_URL = "jdbc:derby://localhost/db";
            String USER = "pavel";
            String PASS = "password";
            kategorijos.clear();
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            stmt = conn.createStatement();
            System.out.println("Podkliucheno");

        }
        catch (Exception e)
        {
            System.out.println("Osibka podkliucenija k DB");
            e.printStackTrace();
        }
    }

Example of one of the use functions

public ArrayList<Kategoriji> polucitSpisokKategorij()
    {
        try
        {
            Podkliucenije();
            String sql = "SELECT * FROM kategoriji";
            ResultSet rs = stmt.executeQuery(sql);

            while(rs.next())
            {
                String nazvanije = rs.getString(1);
                String opisanije = rs.getString("opisanije");
                System.out.println(nazvanije + " - " + opisanije);
                kategorijos.add(new Kategoriji(nazvanije, opisanije));
            }

            rs.close();
            stmt.close();
            conn.close();
        }
        catch (Exception e)
        {
            System.out.println("Osibka podkliucenija k DB");
            e.printStackTrace();
        }

        return kategorijos;
    }
Author: rengetsu, 2019-03-27

1 answers

Why do I have to use Try-catch

You don't need to use try-catch. When calling an unsafe method, you always have a choice:

  • wrap a dangerous method call in a try-catch
  • mark your method throws SomeException
    (sometimes this option is not available when overriding methods or implementing interfaces)

Moreover, there are exceptions in Java that don't need to be intercepted (on this one we will stop a little later).

Exception it is the descendant of the Throwable class, a class that describes all exceptional situations.
Together with Exception, this class inherits the class Error.

  • Error it is used in a situation when restoring the program operation is not possible. Such exceptions are generated by the JVM itself. For example: OutOfMemeryError (out of memory), StackOverflowError(stack overflow), ThreadDeadError(thread death), VirtualMachineError (Virtual machine error cars)

  • Exception the same is used in a situation where the program can be restored and continued.

The Throwable hierarchy looks like this:

              Throwable
              /      \
          Error     Exception
                        |
                RuntimeException

Throwable is of two types:

  • checked ( verifiable )
    These exceptions must be intercepted, or escalate the exception by marking your method throws Exception
    Example: IOException, SQLException, etc.
  • unchecked ( unchecked )
    These situations do not need to be intercepted and described in the method signature
    Example: NullPointerException, IndexOutOfBoundsException, etc
    Unchecked also includes all errors(Error)

What is the meaning of

When working on a method, you can often encounter a situation where an error may occur under some condition, and quite often at this level you simply cannot assess the severity of this error in the application and correctly process it her. How serious this is and how to deal with it further is usually clear on the n-th number of levels above.
All you can do is report a possible error and possibly escalate the problem to a level where it can be resolved.

To do this, call something like this code:

throw new SomeException("У меня возникла проблема, которую я не могу решить!");

After you throw an exception, you should share with the world that there may be problems when calling your method.

For to do this, the following is added to the method signature:

public void myMethod() throws SomeException{
    //...
    throw new SomeException("У меня возникла проблема, которую я не могу решить!");
    //...
}

After that, everyone will know that after they call your method-they can get an Exception in the face.
"Knowledge is power!"...and you can also say " Forewarned means armed!".

In general, when you know that you are dealing with a potentially dangerous method, you can take this into account in your logic and handle the error, if you have the right to do so at this point in the program.
If, however, you do not If you can correctly handle the error in this place, then you mark your method as throwing an exception and thereby shift the responsibility to other shoulders.

In fact, this is a very important point. The most common error is catching an exception ahead of time without proper processing(due to fear of errors or simple misunderstanding of this mechanism). As a result, the program simply begins to behave in an unpredictable way or simply does not perform any actions, expected from it by the user. You can't do that! You should always think about where to handle the exception and how best to respond to it.

What happens when an exception is thrown?

  1. When an exception is thrown, the program is interrupted.
  2. The JVM goes back (from bottom to top) on the execution stack.
    • If there is a point in this stack where this exception is caught, the JVM passes control to this stack. a point.
    • If no one in the stack has caught this exception, then the work ends and information about the event is output to the standard output stream.

What is the profit

In addition to interrupting work and the possibility of transferring control to another point in the program (for which the experts are often criticized) they are also obviously informative.

First: You can leave a message with a description of the problem mistakes.
In the future, many strangers who work with your method may be grateful for it.

Second: Oddly enough, you should also be grateful to Throwable for the stacktrace. It is when the Throwable is created that a snapshot of the execution stack of the current thread is saved.

Third : You can improve and much better describe the low-level exceptions that occur during the work, with exceptions of a higher level of abstraction, while maintaining the cause-and-effect relationship, creating the so-called "chain of events".

 6
Author: Михаил Ребров, 2019-03-27 13:37:23