-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomException.java
More file actions
52 lines (45 loc) · 1.65 KB
/
CustomException.java
File metadata and controls
52 lines (45 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//* Create custom exception and handle the events of different types
//! In Java there are three inbuilt method for handling exceptions
//? 1. toString()
//? 2. printStackTrace()
//? 3. getMessage()
import java.util.Scanner;
class MyClass extends Exception {
@Override
public String toString() { // This method we will be overriding
// ! This method will run when you use sout (e)
// TODO Auto-generated method stub
return "I am toString() Method.";
}
@Override
public String getMessage() { // This method we will be overriding
// ! This method will print the exception message
// TODO Auto-generated method stub
return "you cannot drive the vehicle! and this is the custom exception.";
}
}
public class CustomException {
public static void main(String[] args) {
// ? Create instance of the Scanner class
Scanner sc = new Scanner(System.in);
// ? Get the input number from the user
int num;
System.out.print("Enter the number here : ");
num = sc.nextInt();
System.out.println();
// ? Now handle the exception
if (num < 18) {
try {
throw new MyClass(); // Throw keyword is used to explicitly throw an exception
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
e.printStackTrace(); // This will show where the error it is and which method is called
System.out.println(e);
}
} else {
System.out.println("You can deive vehicle!");
}
sc.close();
}
}