File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Changing unchecked Exceptions to Checked Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Changing unchecked Exceptions to Checked" Watch "Changing unchecked Exceptions to Checked" New topic

Changing unchecked Exceptions to Checked

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46353
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?

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46353
Thank you.

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

I agree. Here's the link:
subject: Changing unchecked Exceptions to Checked
It's not a secret anymore!