Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Changing unchecked Exceptions to Checked

 
Campbell Ritchie
Sheriff
Posts: 48386
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every now and again I think it would be useful to throw a checked Exception rather than returning a null value.
So I think which Exception to use, and NullPointerException comes to mind. So I write "throws NullPointerException," and "throw new NullPointerException();" and let the compiler at it . . . and nothing happens.
Because NullPointer is an unchecked Exception. Not like IOException, where I get told off if I don't cover the code liberally with try-catches.

Is there any way of changing it so it behaves as a checked Exception?

I have tried all sorts of things, looking through the API and going through the source code for Exception and NullPointerException, and not found any way to do it. Is it possible at all?
Or ought I to look for a different Exception?

CR
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few exceptions in the API exist in both checked and unchecked forms: NoClassDefFoundError and ClassNotFoundException, for example, are basically the same thing, used in different contexts. But there's no general solution.

There's no Exception in the standard API that represents a general "can't compute a result, so have to return null" that comes to mind; I'd simply define my own. In my code, I find that unless I'm implementing someone else's interface, I rarely throw an exception from the API, preferring to use custom ones.
 
Campbell Ritchie
Sheriff
Posts: 48386
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.

It seems I was right as far as I had got.

Campbell
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic