Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java's exception handling mechanism an example of the Chain of Responsibility design pattern?

I have been reading about the Chain of Responsibility design pattern which basically allows a decoupling between the sender of a request and receiver of the request. The request can be passed along a chain until someone is ready to consume the request. Now in Java when we specify that a method is capable of throwing an Exception we let the caller of the method handle the exception. If it is not interested it can further propagate the exception up the chain. So can this process be cited as an application of the Chain of Responsibility design pattern?

like image 456
Geek Avatar asked Mar 16 '13 06:03

Geek


People also ask

Is exception handling Chain of Responsibility?

Java exception handling is another example of chain of responsibility design. When an error occurs, the exception call will look for a handling class. If there is no handler, the super Exception class will be called to throw the exception. Otherwise, the handler class will handle it.

What is considered an example of Chain of Responsibility pattern?

One of the great example of Chain of Responsibility pattern is ATM Dispense machine. The user enters the amount to be dispensed and the machine dispense amount in terms of defined currency bills such as 50$, 20$, 10$ etc. If the user enters an amount that is not multiples of 10, it throws error.

Which design pattern is used in exception handling?

Generally a try/catch/finally block is written for handling exception which could go terribly wrong very soon. If you are logging exception in catch block you have got it wrong already. If you are trying to recover from the exception and continuing the code flow then you are right.

What type of design pattern is Chain of Responsibility?

In object-oriented design, the chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects.


1 Answers

You are right. Exception handling in Java is based on Chain of responsibility pattern In this pattern:

  1. Sender will not know which object in the chain will serve its request
  2. Each node in the chain may decide to serve the request --> catching an exception and
    wrapping it with an Application specific exception
  3. Each node can forward the request --> throwing exception to the immediate caller
  4. None of the node can serve the request --> Leaves the job with the caller

Hence, Exception handling is a Chain of responsibility pattern

like image 57
Ezhil V Avatar answered Sep 22 '22 15:09

Ezhil V