Always Catch Most Specific Exception

 class​ TransmissionParser {
 static​ Transmission parse(String rawMessage) {
 if​ (rawMessage != ​null
  && rawMessage.length() != Transmission.MESSAGE_LENGTH) {
 throw​ ​new​ IllegalArgumentException(​"Bad message received!"​);
  }
 
  String rawId = rawMessage.substring(0, Transmission.ID_LENGTH);
  String rawContent = rawMessage.substring(Transmission.ID_LENGTH);
 try​ {
 int​ id = Integer.parseInt(rawId);
  String content = rawContent.trim();
 return​ ​new​ Transmission(id, content);
» } ​catch​ (Exception e) {
 throw​ ​new​ IllegalArgumentException(​"Bad message received!"​);
  }
  }
 }

Exceptions in Java are part of a relatively complex type hierarchy. When you catch an exception, you ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.