019-002-007
Basic try-catch-finally Syntax
Easy
Problem Description
Exception Handling: Division by Zero Validation
In this problem, you will implement a static divide(int a, int b) method that throws IllegalArgumentException when the divisor is zero.
Learning Objective: Understand how to validate method arguments and explicitly throw exceptions for invalid values
Overview
Create a method that performs integer division. When the divisor is 0, explicitly throw an IllegalArgumentException to notify the caller of the error. It is important to validate input yourself and throw an appropriate exception rather than relying on the Java runtime.
Specifications
Main Class
- Method:
static int divide(int a, int b)- If b is 0: throw
IllegalArgumentException- Message: "Divisor must not be zero"
- If b is not 0: return the result of
a / b
- If b is 0: throw
Test Cases
- Valid: divide(10, 2) → 5 (no exception)
- Valid: divide(0, 5) → 0 (no exception)
- Invalid: divide(10, 0) → IllegalArgumentException
- Invalid: divide(-15, 0) → IllegalArgumentException
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up