Skip to content

Instantly share code, notes, and snippets.

@didyhu
Last active May 23, 2016 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didyhu/67735bd1922badf9d6276d43c9aaf599 to your computer and use it in GitHub Desktop.
Save didyhu/67735bd1922badf9d6276d43c9aaf599 to your computer and use it in GitHub Desktop.
Handling exceptions in java projects

There are two types of exceptions in java language.

  • Checked Exceptions
  • Runtime Exceptions

A Checked Exception is a part of the method signature, with the method name, arguments and returns. So if a method throws a checked exception, then the caller should have the knowlege about the exception, the deal with it. Thus we say a checked exception is a Exposing of the inner logic of a method.

And anothor way to classify the exceptions:

  • Expected Exceptions
  • Unexpected Exceptions

The earlier one is most like the business logic exceptions we throws out under some certain state, like illegal user input, illegal order state, etc. We know well about these exceptions, and have a way to handle them, sometimes they are parts of logic branches.

The later one is most like some thing wrong happenning accidently, like IO error, database error, etc. We have no way to expect when and where they will come out. The most proper way we can deal them is to preserve the context, or just write down the logs.

I just guess the the Checked Exceptions were supposed to be the Excepted Exceptions, and the Runtime Exception to be the Unexcepted Exceptions. But on reality, they are not. So we just throw the Checked/Unchecked concepts away, and write all custom exceptions in Runtime Exceptions, and dividing them into Excepted/Unexcepted Exceptions.

And how?

My way is, use only IllegalArgumentException and IllegalStateException, when it is a expected exception, I throw it with a message starting with "@", otherwise, no "@". Then the final exception handler reads the starting letter: If it is a "@", it is a expected exception, so the message can be friendly to end users, and will be passed to the users. If there isn't a "@", it is a unexpected exception, the message is not suitable for the users, so I pass the user only a "Error" alert, meanwhile write the exception trace into the log.

There is no custom exception type, only a rule, a "convention".

Other way, if we do have to work with a custom type exception, I prefer:

  1. Every lib defines a own custom type Runtime exception, with an errCode and an errMessage field.
  2. Every lib referes other libs, never throw the other libs exception types, but only their own exceptios.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment