-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathException_custom.java
More file actions
66 lines (58 loc) · 1.98 KB
/
Copy pathException_custom.java
File metadata and controls
66 lines (58 loc) · 1.98 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
author: Jaydatt Patel
Exception handing:
try{
//statements that may cause an exception
}
catch (){
// error handling code
}
..catch (){
// error handling code
}
// optional
finally {
// this block of code to be always executed after try block ends even exception generated or not
}
Custom Exception : New class of error can be created by extending exisiting error class of java libraries.. This new class of exception can be created like any other ordinary class. However, this class
will have to extend one of the below classes
1. java.lang.Throwable
2. java.lang.Exception
3. java.lang.RuntimeException
*/
import java.util.Scanner;
class AgeException extends Exception {
// the default constructor
AgeException() {
System.out.println("Invalid Age encountered");
}
}
public class Exception_custom {
// The method that throws the custom exception should explicitly state them. In the below example the method 'validate' throws exception AgeException
public static void validate(int age) throws AgeException
{
if (age <= 0) {
throw(new AgeException()) ; // throw the specific custom exception
}
}
public static void main(String args[])
{
boolean valid_inputs = false;
int age = 0;
Scanner scn = new Scanner(System.in);
while (valid_inputs == false)
{
try {
System.out.println("Enter age : ");
age = scn.nextInt();
validate(age);
valid_inputs = true;
}
catch (Exception e) {
valid_inputs = false;
System.out.println("Re-enter inputs!");
}
}
System.out.println("Inputs valid!");
}
}