How to handle invalid argument in Java

6 Answers

0 votes
public class ArgumentCheck {
    public static void printNumber(int num) {
        if (num < 0) {
            throw new IllegalArgumentException("Negative numbers are not allowed.");
        }
        System.out.println("Processing number: " + num);
    }

    public static void main(String[] args) {
        try {
            printNumber(-6); // Throws exception
        } catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

 
 
/*
run:
 
ERROR!
Error: Negative numbers are not allowed.
 
*/

 



answered May 20, 2025 by avibootz
0 votes
import java.util.Scanner;

public class ValidateInput {
    public static boolean isValid(int num) {
        return num >= 0;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();

        if (!isValid(num)) {
            System.err.println("Invalid input: Negative numbers are not allowed.");
        } else {
            System.out.println("Valid input: " + num);
        }

        scanner.close();
    }
}

 
 
/*
run:
 
Enter a number: -8
Invalid input: Negative numbers are not allowed.
 
*/

 



answered May 20, 2025 by avibootz
0 votes
import java.util.Optional;

public class SafeProcessing {
    public static Optional<Integer> safeProcessNumber(int num) {
        return num < 0 ? Optional.empty() : Optional.of(num * 2);
    }

    public static void main(String[] args) {
        Optional<Integer> result = safeProcessNumber(-3);
        
        System.out.println(result.orElseThrow(() -> new IllegalArgumentException("Invalid argument detected.")));
    }
}

 
 
/*
run:

ERROR!
Exception in thread "main" java.lang.IllegalArgumentException: Invalid argument detected.
	at SafeProcessing.lambda$main$0(Main.java:11)

*/

 



answered May 20, 2025 by avibootz
0 votes
import java.util.Objects;

public class RequireNonNullExample {
    public static void printName(String name) {
        // Validate that name is not null
        Objects.requireNonNull(name, "Name cannot be null");
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        printName("Bob"); 
        
        try {
            printName(null); // This will throw a NullPointerException
        } catch (NullPointerException e) {
            System.err.println("Exception caught: " + e.getMessage());
        }
    }
}


 
 
/*
run:

Hello, Bob!
Exception caught: Name cannot be null

*/

 



answered May 20, 2025 by avibootz
0 votes
public class ExceptionExample {
    public static void validateAge(int age) throws Exception {
        if (age < 18) {
            throw new Exception("Age must be 18 or older.");
        }
        System.out.println("Valid age: " + age);
    }

    public static void main(String[] args) {
        try {
            validateAge(14); // This will throw an exception
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }
}


 
 
/*
run:

Exception: Age must be 18 or older.

*/

 



answered May 20, 2025 by avibootz
0 votes
import java.util.Objects;

public class CheckIndexExample {
    public static void getElement(int[] arr, int index) {
        // Ensure index is within array bounds
        Objects.checkIndex(index, arr.length);
        
        System.out.println("Element at index " + index + ": " + arr[index]);
    }

    public static void main(String[] args) {
        int[] numbers = {5, 8, 9, 3, 0, 1};

        try {
            getElement(numbers, 1); // Valid index
            getElement(numbers, 7); // Out of bounds, throws exception
        } catch (IndexOutOfBoundsException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

 
 
/*
run:

Element at index 1: 8
ERROR!
Error: Index 7 out of bounds for length 6

*/

 



answered May 20, 2025 by avibootz

Related questions

4 answers 304 views
4 answers 329 views
4 answers 271 views
4 answers 271 views
3 answers 221 views
3 answers 227 views
...