简体   繁体   中英

Is it a good idea to throw an Unchecked Exception for bad configuration?

My application uses a config file with a lot of configurable items in it.

For instance, you can specify a custom keystore with a custom alias to be used for WebService connections (instead of the default JVM javax.net.ssl.keystore ).

During runtime, we might discover that this alias does not exist in the keystore, so we might want to throw an exception. Because this is a crucial part of the application (and we can't expect the application to function properly until the config is fixed), I'm thinking throwing an Unchecked Exception is a good idea here.

Am I right in thinking that way?

Would it make sense to create a custom ConfigurationException (which extends RuntimeException ) to throw in this case?

Checked Exceptions are thrown to notify the users of your methods that the method can throw a particular exception. So that the users can decide what to do when we get that exception.

If your requirement is "Application should not proceed unless the configurations are correct" and there is no method user can run to circumvent it (in try-catch block) then I do not see any reason to make it a checked Exception (Why to make users do unnecessary work if we know it is of no use).

So, in this case I would also go for unchecked Exception.

I think you should create a checked exception and when you catch it, end the program in catch block after displaying a message or something. Unchecked exceptions are for programming errors and should be corrected by the developer. Check exceptions are for conditions that might happen but we have no control over it. You know the config file may be corrupted but you cannot prevent it from happening and cannot control it. I would go with checked exception.

Unchecked exception indicate a bug in the program or a system error. For example, ArrayIndexOutOfBoundsException or NullPointerException shouldn't occur in a program, and if they occur, they usually indicate a bug.

When validating user input, either direct user input or user input via a configuration file, an exception does not indicate a bug. Therefore it should be a checked exception, to remind the programmer who calls your method that an exception is not unlikely to occur and must be caught. By catching the exception you can produce a user-friendly error message which points to a solution. (You don't want the end user to see the Java-generated Exception in thread ... message!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM