Handling exceptions
Exceptional cases should be handled in Java using exceptions. The ClassCastException
is there and it happens when the sort tries to compare String
to Integer
using StringComparator
, and to do that, it tries to cast an Integer
to String
.
When an exception is thrown by the program using the throw
command, or by the Java runtime, the execution of the program stops at that point, and instead of executing the next command, it continues where the exception is caught. It can be in the same method, or in some calling method up in the call chain. To catch an exception, the code throwing the exception should be inside a try
block, and the catch statement following the try
block should specify an exception that is compatible with the exception thrown.
If the exception is not caught, then the Java runtime will print out the message of the exception along with a stack trace that will contain all the classes, methods, and line numbers on the call stack at the time of the exception. In...