I'm reading the source of XWalkUIClientInternal and I ran into the following code:
switch(type) {
case JAVASCRIPT_ALERT:
return onJsAlert(view, url, message, result);
case JAVASCRIPT_CONFIRM:
return onJsConfirm(view, url, message, result);
case JAVASCRIPT_PROMPT:
return onJsPrompt(view, url, message, defaultValue, result);
case JAVASCRIPT_BEFOREUNLOAD:
// Reuse onJsConfirm to show the dialog.
return onJsConfirm(view, url, message, result);
default:
break;
}
assert(false);
return false;
I've never really seen this technique nor really thought about it before, but I guess this essentially means "this is unreachable code and should not happen ever", and crash the app no matter what. Although technically you can do that with a Throwable, as long as it's not caught.
So my question is, which one is better and why, assert(false)
or throwing a RuntimeException
, or maybe an Error
?
The biggest difference between
(The parenthesis are not needed,
assert
is not a function but a statement.) andis that the assertion can be disabled. Actually, it is disabled by default unless the JVM is started with the
-ea
(“enable assertions”) flag. If assertions are enabled,assert false
will unconditionally throw anAssertionError
which derives fromError
. But since assertions can be disabled, there are two problems,return
statement after theassert
(which is mostly clutter).Therefore, in the above case, I'd certainly go with an explicit (and more concise)
instead of an
assert
followed by a dummyreturn
.As mentioned in the comments, this is assuming that
type
is an internal parameter and an invalid value indicates a bug in the logic itself. If it is an input parameter, it should be validated according to the usual rules and anIllegalArgumentException
be thrown if validation fails.Following the Oracle guidelines (Programming with assertions), assertions was designed for testing purposes:
In your example, the developer assumed that the code never reaches the
assert
statement. If, by rare occurrence it does, theassert(false)
will throw anError
(since it should never get there). This was done for testing purposes. So, use assert purely for testing purposes.