TurkuBasicOOPinJava / Week 5: Class hierarchies /14A. More exercises: Custom Exceptions+++
KaiquanMah's picture
class CustomException extends Exception
0dd8036 verified
raw
history blame
2.13 kB
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());
}
}
}