Exceptions are Objects

When a class designer believes that an exceptional condition is recoverable, the checked exception should be thrown. But, many programmers (and I am guilty of this as well) tend to forget that an Exception is an object, and thus its subclasses can have additional states/behaviors added to them. In most cases, Exceptions are thought of as just wrappers around messages that describe what went wrong.

However, exceptions can do more?and in the case of checked exceptions, they should do more. Since checked exceptions expect the caller to recover from exceptional conditions, they should provide information through additional fields/methods that the caller can use for that recovery.

For instance, say you have a method that builds a request object based on some byte sequence received from communication port:

 	public Request getFromBytes(byte[] bytes)	  throws InvalidMessageLengthException {...}

You throw a checked exception, because you expect the caller to recover from the situation by reading additional bytes from the communication channel.In order to provide the caller with more information, your exception might look like this:

 class InvalidMessageLengthException  extends Exception{...  public int expectedLength() {...}  public int actualLength() {...}}

By calling the methods of the caught exception, the caller will know how many more bytes to read from the communication channel before attempting to call the method again.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS