This project illustrates the behavior of the finally block when an exception occurs but is not caught by a catch block. It proves that the Java Virtual Machine guarantees the execution of the finally block before the program terminates due to a fatal error, which is essential for resource cleanup.
- Task: Intentionally cause a division by zero error in the
tryblock. - Constraint: Do not use a
catchblock. - Mechanism: Implement a
finallyblock to display a sensor message. - Goal: Observe that the
finallymessage is printed before the program crashes with an exception.
- Java 8+
The try-finally structure is used when we want to ensure specific code runs regardless of success or failure, but we want the exception to propagate further (to the caller or the JVM). In this case, the ArithmeticException is thrown, the finally block executes its print statement, and then the JVM terminates the thread with the error log.
=====================================================================
Sensor reports: finally execution completed. Even in case of a crash.
=====================================================================
The following message comes from the JVM, which terminates the thread
and writes an error to the error log:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.yurii.pavlenko.Solution.main(Solution.java:10)
Process finished with exit code 1
Project Structure:
src/com/yurii/pavlenko/
βββ Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
try {
int result = 5 / 0;
System.out.println("Result: " + result);
} finally {
System.out.println("=====================================================================");
System.out.println("Sensor reports: finally execution completed. Even in case of a crash.");
System.out.println("=====================================================================");
System.out.println();
System.out.println("The following message comes from the JVM, which terminates the thread\n" +
"and writes an error to the error log:");
System.out.println();
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT