SLC S22 Week4 || Exception handling in Java

in #dynamicdevs-s22w46 days ago (edited)


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.

image.png

Image taken from source

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.


image.png

Task 1: Detecting Faulty Sensor Readings

image.png

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

image.png

Explanation
  • 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:

image.png

Output:

image.png

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.

image.png

Task 2: Dynamic Input Validation for an Event

image.png

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

image.png

Output:

image.png

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.

image.png

Task 3: Hierarchical Exception Handling in a Game

image.png


Problem Statement

Design a hierarchy of custom exceptions for handling errors in an RPG game.

Solution

Code:

image.png

image.png

image.png

image.png

Output:

image.png

image.png

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.

image.png

Task 4: Banking System Transaction Errors

image.png

image.png

Problem Statement

Validate transactions in a banking system, handling exceptions such as InsufficientFundsException, InvalidAccountException, and NegativeTransferException.

Solution

image.png

image.png

image.png

Output:

image.png

image.png

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

  1. InsufficientFundsException: Thrown when the sender has insufficient balance.
  2. InvalidAccountException: Thrown when an account does not exist.
  3. 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.

image.png

Task 5: Automating Resource Cleanup

image.png

Problem Statement

Write a program to ensure proper cleanup of file resources, even if exceptions occur.

Solution

image.png

image.png

Output:

image.png

image.png

image.png

Explanation

  1. File Paths: The program attempts to open three files located in the src folder: config.txt, data.txt, and settings.txt.

  2. Reading Files: For each file, it reads and prints the contents using a BufferedReader.

  3. 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.

  4. Closing Files: The finally block ensures each file is closed after processing, even if an error occurred while reading.

  5. 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.

image.png

Task 6: Predicting Future Errors Using Logs

image.png---

Problem Statement

Monitor user activity logs for suspicious login attempts and raise a SuspiciousActivityException for repeated failures.

Solution

image.png

image.png

image.png

Output:

image.png

image.png

Explanation

Code Overview:

  1. Exception Handling:

    • SuspiciousActivityExceptionalert admins when I use it exceed 3 failed login attempts.
  2. 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.
  3. Failed Login Tracking:

    • Failed login attempts are stored for each user.
    • If a user fails 3 times consecutively
      then SuspiciousActivityException is thrown.
  4. Admin Alert:

    • If suspicious activity is detected (3 failed attempts) then the admin (mateenfatima) is alerted.
  5. 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:

  1. User enters username and password.
  2. If the login is incorrect then the program tracks the failed attempt.
  3. After 3 failed attempts an alert is triggered for the admin.
  4. If the login is correct a success message is shown.

So here is the completion of my entry. Feel free to tell me if I have any mistake

image.png

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

Thanks for Reading
Regards @mateenfatima
Sort:  
Loading...