I want to avoid crashes in the release even if something is wrong. That’s why I do not want to throw exceptions that, I know, are not going to be handled.
In Debug mode I want to do it because it’s good to get as much noise as possible when something is wrong during debug.
The problem is that if I do something like:
if (DEBUG_MODE) throw e;
then I need to specify that the method throws an exception but I do not want to do it becasue that is not true in the release.
What’s the best way of dealing with this?
EDIT
PS
My question was not clear sorry.
In my case assertion are not really convenient. The problem is that I already know that something is wrong so I do not have anything to assert. To make it clearer I have unexpected exceptions. Of course you can say: write the code not to have unexpected exceptions. But in case something is wrong I do not want the application to crash. Now I added a function like this:
public static void unexpectedException(String string, Exception e) {
if (Build.DEBUG) {
MyApp.errorLog(string);
throw new RuntimeException(e);
} else
MyApp.errorLog(string, e);
}
Althought all your answers were correct I’ll choose that one that is nearer to what I did
PS2
Another case when the assertion is not really convenient is when you implement a pattern like state. If for some state you expect a method not to ever be called…
If you do not want to use assertions, as you really should, you can derive your exceptions from
RuntimeException. Then you do not have to declare them asthrowsin your method header.That being said, you should really take a look at assertions, or as other replies has said, a proper logging framework.