KaiquanMah commited on
Commit
0dd8036
·
verified ·
1 Parent(s): 90add41

class CustomException extends Exception

Browse files
Week 5: Class hierarchies/14A. More exercises: Custom Exceptions+++ ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Let's conclude this section by discussing inheritance and OWN EXCEPTIONS.
2
+
3
+ In Java, a 'new exception class' can be defined by inheriting class Exception.
4
+ Usually, it's enough to define a constructor which gets a message (a String) as an argument and
5
+ then calls the super class constructor.
6
+
7
+ Consider the following example:
8
+ class TooLongMessageException extends Exception {
9
+ public TooLongMessageException(String message) {
10
+ super(message);
11
+ }
12
+ }
13
+
14
+ Own exception can be thrown like any other exception.
15
+
16
+
17
+
18
+
19
+ Note that a method that may throw a 'checked exception', must declare this with the 'throws' keyword.
20
+ This also concerns the constructor.
21
+
22
+ class TextMessage {
23
+ private String sender;
24
+ private String recipient;
25
+ private String message;
26
+
27
+ public TextMessage(String sender, String recipient, String message)
28
+ throws TooLongMessage {
29
+ this.sender = sender;
30
+ this.recipient = recipient;
31
+ setMessage(message);
32
+ }
33
+
34
+ // METHOD 'throws' OUR OWN CUSTOM-DEFINED EXCEPTION
35
+ public void setMessage(String message) throws TooLongMessage {
36
+ if (message.length() > 160) {
37
+ throw new TooLongMessageException("Maximum length is 160 characters");
38
+ }
39
+ this.message = message;
40
+ }
41
+ }
42
+
43
+
44
+
45
+
46
+
47
+ An exception like this needs to be caught when the method is called:
48
+ public static void main(String[] args) {
49
+ Scanner reader = new Scanner(System.in);
50
+ while (true) {
51
+ System.out.print("Give sender, empty line exits: ");
52
+ String sender = reader.nextLine();
53
+
54
+ if (sender.equals("")) {
55
+ break;
56
+ }
57
+
58
+ System.out.print("Give recipient: ");
59
+ String recipient = reader.nextLine();
60
+
61
+ System.out.print("Give message: ");
62
+ String message = reader.nextLine();
63
+
64
+ // TRY-CATCH TO CATCH EXCEPTION 'e'
65
+ try {
66
+ TextMessage textMessage= new TextMessage(sender, recipient, message);
67
+ }
68
+ catch (TooLongMessageException e) {
69
+ System.out.println("Could not create a message: " + e.getMessage());
70
+ }
71
+ }
72
+ }
73
+
74
+
75
+
76
+
77
+
78
+
79
+