finally block is a construct in Java that is often used in conjunction with the try-catch block and is used to place code that you want to always run. After the codes in the try block are executed, the finally block always runs, regardless of whether an exception occurs.
try { // Hata oluşabilecek kodlar } catch (Exception e) { // Hata yakalama işlemleri } finally { // Mutlaka çalıştırılacak kodlar }
public class FinallyExample { public static void main(String[] args) { try { System.out.println("Try bloğu çalışıyor."); int result = 10 / 0; // Bu satır ArithmeticException oluşturur. } catch (ArithmeticException e) { System.out.println("Catch bloğu çalışıyor: " + e.getMessage()); } finally { System.out.println("Finally bloğu her zaman çalışır."); } } }
Try bloğu çalışıyor. Catch bloğu çalışıyor: / by zero Finally bloğu her zaman çalışır.
In this example, when an ArithmeticException occurs in the try block, the catch block catches this error and prints a message. However, whether there is an error or not, the finally block always runs and the "Finally block always runs." writes the message on the screen.
The finally block works even when exiting with a return statement, but if the JVM shuts down (like System.exit(0)) the finally block may not run.
The above is the detailed content of Finally. For more information, please follow other related articles on the PHP Chinese website!