File size: 2,130 Bytes
0dd8036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Let's conclude this section by discussing inheritance and OWN EXCEPTIONS.

In Java, a 'new exception class' can be defined by inheriting class Exception. 
Usually, it's enough to define a constructor which gets a message (a String) as an argument and 
then calls the super class constructor.

Consider the following example:
class TooLongMessageException extends Exception {
    public TooLongMessageException(String message) {
        super(message);
    }
}
 
Own exception can be thrown like any other exception.




Note that a method that may throw a 'checked exception', must declare this with the 'throws' keyword. 
This also concerns the constructor.

class TextMessage {
    private String sender;
    private String recipient;
    private String message;
    
    public TextMessage(String sender, String recipient, String message) 
            throws TooLongMessage {
        this.sender = sender;
        this.recipient = recipient;
        setMessage(message);
    }

    // METHOD 'throws' OUR OWN CUSTOM-DEFINED EXCEPTION
    public void setMessage(String message) throws TooLongMessage {
        if (message.length() > 160) {
            throw new TooLongMessageException("Maximum length is 160 characters");
        }
        this.message = message;
    }
}
 




An exception like this needs to be caught when the method is called:
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    while (true) {
        System.out.print("Give sender, empty line exits: ");
        String sender = reader.nextLine();
        
        if (sender.equals("")) {
            break;
        }
        
        System.out.print("Give recipient: ");
        String recipient = reader.nextLine();
        
        System.out.print("Give message: ");
        String message = reader.nextLine();

        // TRY-CATCH TO CATCH EXCEPTION 'e'
        try {
            TextMessage textMessage= new TextMessage(sender, recipient, message);
        } 
        catch (TooLongMessageException e) {
            System.out.println("Could not create a message: " + e.getMessage());
        }
    }
}