summary refs log tree commit diff stats
path: root/java/code/CustomExceptionExample.java
diff options
context:
space:
mode:
Diffstat (limited to 'java/code/CustomExceptionExample.java')
-rw-r--r--java/code/CustomExceptionExample.java26
1 files changed, 26 insertions, 0 deletions
diff --git a/java/code/CustomExceptionExample.java b/java/code/CustomExceptionExample.java
new file mode 100644
index 0000000..9443c6e
--- /dev/null
+++ b/java/code/CustomExceptionExample.java
@@ -0,0 +1,26 @@
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+class NegativeNumberException extends Exception {
+    public NegativeNumberException(String message) {
+        super(message);
+    }
+}
+
+public class CustomExceptionExample {
+    public static void main(String[] args) {
+        Scanner scanner = new Scanner(System.in);
+        try {
+            System.out.print("Enter an integer: ");
+            int userInput = scanner.nextInt();
+            if (userInput < 0) {
+                throw new NegativeNumberException("Number cannot be less than zero");
+            }
+            System.out.println("You entered: " + userInput);
+        } catch (InputMismatchException e) {
+            System.out.println("Input must be an integer.");
+        } catch (NegativeNumberException e) {
+            System.out.println(e.getMessage());
+        }
+    }
+}