
Mastering Java Exception Handling: From Tip Calculator to Real-World Selenium Automation
Whether you’re a Java beginner or a test automation engineer, understanding exception handling is essential. It protects your code from crashing and provides meaningful feedback when things go wrong.
What is an Exception in Java?
An exception is an event that disrupts the normal flow of execution. Java provides a mechanism to handle such conditions using try, catch, and finally blocks.
Exception Types in Java
Checked Exceptions
Must be handled with a try-catch block or declared using throws.
Examples: IOException, FileNotFoundException
Unchecked Exceptions
Occur at runtime due to bugs or invalid logic.
Examples: NullPointerException, ArithmeticException, InputMismatchException
Common Java Exceptions and Use Cases
Common Java Exceptions With Examples
1. InputMismatchException
Occurs when the user enters a value of the wrong type.
import java.util.*;
public class InputMismatchDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = sc.nextInt(); // Will fail if input is "abc"
System.out.println("You entered: " + num);
} catch (InputMismatchException e) {
System.out.println("Error: Please enter a valid number.");
}
}
}

2. NumberFormatException
Thrown when a string cannot be parsed to a number.
public class NumberFormatDemo {
public static void main(String[] args) {
try {
String str = "abc";
int num = Integer.parseInt(str); //Fails here
} catch (NumberFormatException e) {
System.out.println(" Error: Cannot convert string to number.");
}
}
}

3. ArithmeticException
Happens on illegal arithmetic operations like division by zero.
public class ArithmeticDemo {
public static void main(String[] args) {
try {
int x = 10 / 0; //Division by zero
} catch (ArithmeticException e) {
System.out.println(" Error: Cannot divide by zero.");
}
}
}
4. ArrayIndexOutOfBoundsException
Accessing an invalid array index throws this exception.
public class ArrayIndexDemo {
public static void main(String[] args) {
try {
int[] nums = {1, 2, 3};
System.out.println(nums[5]); //Index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(" Error: Invalid array index.");
}
}
}

5. IllegalArgumentException
Manually thrown when method arguments are illegal or inappropriate.
public class IllegalArgDemo {
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Age: " + age);
}
public static void main(String[] args) {
try {
setAge(-5); // Invalid argument
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

6. FileNotFoundException / IOException
Occur during file operations when files are missing or unreadable.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent.txt"); //File doesn't exist
reader.read();
} catch (FileNotFoundException e) {
System.out.println("Error: File not found.");
} catch (IOException e) {
System.out.println("Error reading file.");
}
}
}

7. NullPointerException
Thrown when accessing a method or property of a null object
public class NullPointerDemo {
public static void main(String[] args) {
try {
String name = null;
System.out.println(name.length()); // Null access
} catch (NullPointerException e) {
System.out.println("Error: Cannot use methods on a null object.");
}
}
}

Full Project: Java Tip Calculator with Exception Handling
A simple Java console app that:
- Accepts bill amount and tip percentage
- Handles wrong input
- Uses multiple exceptions to prevent crashes
package com.kshitij;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
public class TipCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double amount = 0;
double tipPercent = 0;
try {
// Input bill amount
System.out.println("Enter the bill amount: ");
amount = scanner.nextDouble();
scanner.nextLine(); // clear newline
// Handle invalid bill amount
if (amount <= 0) {
throw new IllegalArgumentException("Bill amount must be greater than 0.");
}
// Tip selection
System.out.println("Choose the tip percentage: 10, 15, 20 or type 'custom'");
String tipInput = scanner.nextLine().trim();
// Handle standard tip values
if (tipInput.equals("10") || tipInput.equals("15") || tipInput.equals("20")) {
tipPercent = Double.parseDouble(tipInput); // could throw NumberFormatException
} else if (tipInput.equalsIgnoreCase("custom")) {
System.out.println("Enter your custom tip percentage:");
String customTipInput = scanner.nextLine().trim();
tipPercent = Double.parseDouble(customTipInput); // could throw NumberFormatException
if (tipPercent <= 0 || tipPercent > 100) {
throw new IllegalArgumentException("Custom tip must be between 1 and 100.");
}
} else {
throw new RuntimeException("Invalid tip input. Please choose 10, 15, 20, or 'custom'.");
}
// Tip calculation - potential ArithmeticException (if amount is 0)
double tipAmount = (tipPercent / 100) * amount;
double totalAmount = amount + tipAmount;
// Format and display output
NumberFormat currency = NumberFormat.getCurrencyInstance(new Locale("en", "CA"));
System.out.println("\n--- Tip Calculation Result ---");
System.out.println("Tip Amount: " + currency.format(tipAmount));
System.out.println("Total Amount to Pay: " + currency.format(totalAmount));
System.out.println("--------------------------------");
} catch (InputMismatchException e) {
System.out.println("Input Error: Please enter numeric values only (e.g., 1000, 15.5).");
} catch (NumberFormatException e) {
System.out.println("Format Error: Couldn't convert your input into a number.");
} catch (IllegalArgumentException e) {
System.out.println("Invalid Argument: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unexpected Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}
Test Cases:
- bill = abc → InputMismatch
- tip = 200 → IllegalArgument
- tip = abc → NumberFormatException
Bonus: Selenium + Java Exception Handling
Here’s a Selenium test example that:
- Catches common exceptions
- Takes screenshots on failure
- Always closes the browser java
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
---
public class LoginTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("wrongpass");
driver.findElement(By.id("loginButton")).click();
WebElement welcome = driver.findElement(By.id("welcome"));
System.out.println("Login Success: " + welcome.getText());
} catch (NoSuchElementException e) {
System.out.println("Element missing: " + e.getMessage());
takeScreenshot(driver, "NoElement");
} catch (TimeoutException e) {
System.out.println("Timeout: " + e.getMessage());
takeScreenshot(driver, "Timeout");
} catch (WebDriverException e) {
System.out.println("WebDriver issue: " + e.getMessage());
takeScreenshot(driver, "WebDriver");
} catch (Exception e) {
System.out.println("Unknown error: " + e.getMessage());
takeScreenshot(driver, "General");
} finally {
driver.quit();
}
}
public static void takeScreenshot(WebDriver driver, String name) {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File(\"./screenshots/\" + name + \".png\"));
} catch (IOException e) {
System.out.println(\" Screenshot failed: \" + e.getMessage());
}
}
}
Summary
Whether you’re building a calculator or a web automation test:
- Handle expected AND unexpected inputs
- Catch specific exceptions for better debugging
- Ensure your application never crashes
By understanding and applying exception handling, your Java programs will be safer, smarter, and more professional.