O'Reilly logo

Java By Comparison by Jörg Lenhard, Linus Dietz, Simon Harrer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required