T
T
Timur Pokrovsky2020-04-20 17:02:54
Java
Timur Pokrovsky, 2020-04-20 17:02:54

What is the meaning of finally?

Java and c# have a try-catch-finally construct. Why is finally needed if

try {
    Integer.parseInt("test");
    System.out.println("try");
}
catch (Exception ex) {
    System.out.println("catch");
}
finally {
    System.out.println("finally");
}

and

try {
    Integer.parseInt("test");
    System.out.println("try");
}
catch (Exception ex) {
    System.out.println("catch");
}
System.out.println("finally");

output the same thing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-04-20
@Makaroshka007

Finally guarantees the execution of the code, regardless of whether there was an error or not.
But what happens if the code that handles the exception throws the exception itself?

try
{
  throw new ArgumentException();
}
catch(Exception)
{
      // any new exception thrown here
} 
CodeCleanup();

In this case, the execution of the logic will be interrupted, respectively, the CodeCleanup method will not be executed.
This can happen, for example, when calling methods that perform certain network operations that fall off on Timeout. In such a case, the Nth number of repeated calls to the same method are usually made in order to eliminate problems associated with network stability.
Finally solves this problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question