MongoException inherits RuntimeException - is it a good design?

I see that com.mongodb.MongoException inherits from java.lang.RuntimeException, what seems to be a bad design. RuntimeException is “unchecked” exception, so it is not needed to be declared in method signature. RuntimeException should not be catch because it indicates a programmatic problem which should be fixed in source code, i.e. NullPointerException is RuntimeException, and it generally should never be caught, that’s why RuntimeException is not declared in method signature.

See details in Java documentation: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

On the other hand, MongoException and its derived exceptions are intended to be caught in clients code, so it violates the RuntimeException idea. MongoException is a part of method’s API (for example for insertOne() or InsertMany() methods), so it should be declared in method signature, but it is not. MongoExceptions are only mentioned in JavaDocs.

Summarizing, in my opinion MongoException should extends java.lang.Exception directly, and java.lang.RuntimeException should be removed from inheritance hierarchy, then MongoException and its derivatives should be explicitly declared in methods` signatures.

1 Like

Hi @sgnsajgon,

Very interesting question. There are few possible explanations:

I think it is completely reasonable for MongoException to be checked. Most java programmers will abstract out the data layer anyway, so the checks only really need to be done in the data layer.

Looking at the current code base, the uses of IllegalArgumentException, IllegalStateException, and UnsupportedOperationException seem for the most part appropriate. There are a quite a few RuntimeException throws that could still be replaced with a more appropriate exception.

Read all here:
https://jira.mongodb.org/browse/JAVA-265

More useful link:
http://www.javapractices.com/topic/TopicAction.do?Id=129

Kanika

1 Like