This project demonstrates the usage of the finally block in Java. In software development, certain actions (like closing a database connection or sending a final status report) must occur regardless of whether an error occurred. This simulation uses a cleaning robot to show how the finally block guarantees execution of completion messages.
- Task: Divide 10 tasks by 2 tasks per minute to calculate duration.
- Mechanism: Implement a
try-finallystructure. - Guarantee: Use the
finallyblock to ensure the robot always reports its status. - Goal: Display the calculation result and the mandatory final status message.
- Java 8+
The finally block follows a try or catch block. Its primary characteristic is that it always executes, even if an exception is thrown or a return statement is encountered. This makes it the ideal place for cleanup logic or mandatory logging, ensuring system reliability.
Cleaning time: 5 minutes
Robot has finished its work. Execution completed.
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
try {
int totalTasks = 10;
int tasksPerMinute = 2;
int duration = totalTasks / tasksPerMinute;
System.out.println("Cleaning time: " + duration + " minutes");
} finally {
System.out.println("Robot has finished its work. Execution completed.");
}
}
}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