SLC S22 Week4 || Exception handling in Java
Greetings to All
I wish you all will be great by the blessings and mercy of Almighty Allah and enjoying beautiful days of your life. So Today I am here to participate in the Steemit Learning challenge season 22 week 4 and the topic of the contest is Exception handling in Java*. As already 3 weeks have been passed in which we have learned the basic fundamentals of JavaScript and today we will learn further so let's start by answering our home tasks.
Introduction |
---|
Welcome to 4th week of learning challenge this week we will delve deeper into exceptional handling that is an essential skill for building robust error tolerant applications. Through this exploration we will be able to write and maintain user friendly code that will gracefully manage the errors and unexpected situations. This post will include detailed explanation and solution for all tasks.
Task 1: Detecting Faulty Sensor Readings |
---|
Problem Statement
Managing the temperature data collected from multiple sensors in factory. Handle exceptions for any valid values ,such as negative temperatures while continue to process valid readings.
Solution
- The program will iterate over the sensor readings.
- if there is any negative value, it throws an IllegalArgumentException and logs the error.
- The valid are displayed in the console.This was just the code of the example and it proceed with the readings of the given string now lets make it more flexible and take values from user.
Code:
Output:
Explanation:
Here I used the scanner object to read the user input from the console. The loop allows user to input multiple readings ensuring flexibility.
User can enter the stop to stop the reading and display the output or result of the reading. I used the try-catch block
to validate readings.
- If the input is not a valid number then a NumberFormatException is caught.
- If the number is negative then an IllegalArgumentException is thrown and logged.
Then the Valid readings are added up to the array list for later processing.
Task 2: Dynamic Input Validation for an Event |
---|
Problem Statement
Validate participant ages for an event. If the input age is out of the range 18-60, throw a custom exception InvalidAgeException
.
Solution
Output:
Explanation
So lets explain our code this program is designed to validate the age the participant age must be between the 18 and 60 .It is designed to handle age outside of this range.The user will enter stop to exit.InvalidAgeException
is used to throw an error if the age is outside of the the valid range.the program also reads input and checks if it is a valid number and lies within the range. So ,The validateAge
method throws the InvalidAgeException
if the age is invalid and If the input is not number or the age is invalid then the appropriate error messages are displayed on screen.
Task 3: Hierarchical Exception Handling in a Game |
---|
Problem Statement
Design a hierarchy of custom exceptions for handling errors in an RPG game.
Solution
Code:
Output:
Explanation:
This program is a simple RPG game where the player's health starts at 50. Players make choices to attempt moves, check their health, or exit the game.
Custom Exceptions:
HealthException
is thrown when health drops to 0 or below.MoveException
is thrown for invalid moves, reducing health by 10.
Game Flow:
- If a valid move is made, no health is lost.
- Invalid moves reduce health and throw a
MoveException
. - If health reaches 0, a
HealthException
ends the game. - Players can check health status or exit anytime.
Key Methods:
performAction
: Simulates a move and handles health reduction.try-catch
blocks handle exceptions for invalid moves and low health.
The game ends if health reaches 0 or the player chooses to exit.
Task 4: Banking System Transaction Errors |
---|
Problem Statement
Validate transactions in a banking system, handling exceptions such as InsufficientFundsException
, InvalidAccountException
, and NegativeTransferException
.
Solution
Output:
Explanation
The BankingSystem
program actually simulates a banking system with the help of following features:
- Transfer Money: It validates sender and recipient accounts and check out the sufficient funds so we have to ensure that the transfer amount is positive.
- Check Balance: Displays the balance for a valid account.
- Exit: Safely exits the program.
Custom Exceptions
- InsufficientFundsException: Thrown when the sender has insufficient balance.
- InvalidAccountException: Thrown when an account does not exist.
- NegativeTransferException: Thrown when the transfer amount is zero or negative.
Program Flow
- A menu lets users choose actions (transfer money, check balance, or exit).
- Transactions are processed through validations, updating balances if valid.
- Errors like invalid accounts or insufficient funds are handled with meaningful feedback.
- Logs track failed transactions for record-keeping.
This ensures safe and clear banking operations.
Task 5: Automating Resource Cleanup |
---|
Problem Statement
Write a program to ensure proper cleanup of file resources, even if exceptions occur.
Solution
Output:
Explanation
File Paths: The program attempts to open three files located in the
src
folder:config.txt
,data.txt
, andsettings.txt
.Reading Files: For each file, it reads and prints the contents using a
BufferedReader
.Error Handling: If a file is missing or there’s an issue, an error message is printed. The program uses a
try-catch
block for this.Closing Files: The
finally
block ensures each file is closed after processing, even if an error occurred while reading.Completion Message: After processing all files, the program prints "All files processed."
Key Points:
- Exception Handling: Catches errors like missing files.
- File Management: Ensures files are properly closed using
finally
. - BufferedReader: Efficiently reads file content line by line.
Task 6: Predicting Future Errors Using Logs |
---|
---
Problem Statement
Monitor user activity logs for suspicious login attempts and raise a SuspiciousActivityException
for repeated failures.
Solution
Output:
Explanation
Code Overview:
Exception Handling:
SuspiciousActivityException
alert admins when I use it exceed 3 failed login attempts.
Login Process:
- Users enter a username and password.
- If the credentials match the validUserCredentials they are successfully logged in.
- If the credentials did not match then failed attempt is logged.
Failed Login Tracking:
- Failed login attempts are stored for each user.
- If a user fails 3 times consecutively
then SuspiciousActivityException is thrown.
Admin Alert:
- If suspicious activity is detected (3 failed attempts) then the admin (
mateenfatima
) is alerted.
- If suspicious activity is detected (3 failed attempts) then the admin (
User Interface:
- Users get feedback after each login attempt with the program or information displaying the number of failed attempts.
- Admin is notified if suspicious activity occurs.
Flow:
- User enters username and password.
- If the login is incorrect then the program tracks the failed attempt.
- After 3 failed attempts an alert is triggered for the admin.
- If the login is correct a success message is shown.
So that was all from my side about the topic and I hope that you all will like to read the post and support the content
I would like to invite
to participate in the contest
Regards @mateenfatima |
---|