开发者

Should your exceptions be named PrinterException or PrintingException

开发者 https://www.devze.com 2023-02-08 16:33 出处:网络
Given an interface like Printer { print() } should it throw PrinterException or PrintingException. I guess PrinterException is more generic in that it can also be used for methods done by the Print

Given an interface like

Printer {
  print()
}

should it throw PrinterException or PrintingException. I guess PrinterException is more generic in that it can also be used for methods done by the Printer that is not actually printing, say something like turnoff().

What if Printer actually had two methods

Printer {
   shutdown() throws PrinterShuttingDownException;
   print() throws Pri开发者_StackOverflow社区ntingException
}

or

Printer {
   shutdown() throws PrinterException;
   print() throws PrinterException;
}


I would argue PrinterException is better because it defines exceptions which aren't necessarily related to the act of printing, which is possible if the arguments aren't correct or it fails for a somewhat unrelated issue like problems logging to a file.

Though, it's subjective so it's up to you.

Edit:
If you have two operations, print and shutdown, then print should throw a PrintingException and shutdown should throw a PrinterShutdownException, both of which would derive from PrinterException. This would allow you to catch specific cases or any exception related to the printer.


I would always have PrinterException. It's an Exception, thrown by the Printer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号