George Silva
George Silva

Reputation: 3484

Details at Exception construction

What are the deep technical details behind creating and using correctly custom exceptions?

I mean, I can see the use of custom exceptions to help control flow around higher layers and perhaps even output correct messages to users all the way up there (away from the base software layers), but what other details would be good/great to always include?

I know all kind of information of why something is exceptional is great to start with, but, what are those tricks you keep up in your sleeves?

And also: when to build custom exceptions?

I would like a insight for all languages, but currently using c#.

Thanks!

Upvotes: 1

Views: 61

Answers (1)

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

Very interesting question. I find detailed exception-handling extremely important, it is one source of stable code. The best thing you can do is customize whenever a general Exception is not detailed enough; i know this sounds obvious but here is an example: You can either throw FileNotFoundException or your own MyFileError.

1) The difference in name is only the first advantage: it tells you immediately that it is one of the methods in YOUR package that failed (in contrast to the dozens of third-party-libraries you will use in large projects, which hopefully also throw customized exceptions, not the standard ones).

2) Even better: you can add information to fields of MyFileError-objects: you can store a string that tells you which file the method tried to load.

This is only a very simple example; think of this more evolved one: You are building a banking system (online-banking or b2b). Instead of a SocketError you have your customized TransactionError which has a field that stores which part of the transaction failed, 2 example states would be "before-authentication" and "monetaryTransactionNonZero", the first one would be harmless and you could just make the system automatically retry a couple of times and then prompt the user to check his network; the second one however would be the critical part in a monetary transaction: the money was subtracted off the holder's account but not yet assigned to the person he wanted to send the money to; in that case your higher level system should issue a rollback (serverside) and an error-message (clientside).

Nothing is worse than having such detailed information at the lower levels but then using a catch(Exception) { System.out.println("an error has occured"); } on the upper levels.

Upvotes: 1

Related Questions