You can find a more detailed explanation of exceptions in my exception tutorial
Exceptions are unexpected or abnormal conditions in a program. When such a condition occurs in a Scala program, it can throw an exception. The normal flow of execution is then interrupted, and continues at the nearest (innermost, most recent) place where this kind of exception is caught.
Errors such as OutOfMemoryError indicate a serious failure, where continuing the program makes no sense.
Other exceptions, however, merely indicate an unexpected or abnormal condition in a program. For instance, a mistake in the input data of a program could cause an exception. Such mistakes can be handled: We say that the exception is "handled" or caught.
For instance, a NumberFormatException might indicate that the user entered an incorrect number, and the correct response would be to print an error message and ask for new input.
A FileNotFoundException means that the file we tried to open does not exist. Depending on the situation, the correct response could be to try a different file name, to ask the user for a different file name, or simply to skip reading the file.
We can catch an exception by enclosing the critical part in a try block, and adding a catch block to handle the exceptions we are interested in:
val str = readLine("Enter a number> ") try { val x = str.toInt printf("You said: %d\n", x) } catch { case e: NumberFormatException => printf("'%s' is not a number\n", str); }If the try block executes normally, then the catch clauses are skipped. But if somewhere inside the try block (including in any method called, directly or indirectly) an exception is thrown, then execution of the try block stops immediately, and continues in the first case of the catch clause that matches the exception. Here, "matches" means that the exception is the same type as the exception type listed in the case.
The code within a catch case is called an exception handler.
When you detect a mistake in the input data, you can throw an exception yourself:
def g(n: Int) { printf("Starting g(%d) ... \n", n) if (n < 0) throw new IllegalArgumentException printf("The value is %d\n", n) printf("Ending g(%d) ... \n", n) }
Note that exceptions are objects, and need to be created using the new keyword.
Assertions are conditions in the program that are tested during the execution. The syntax is
assert(condition)If the condition is true, nothing particular happens. If the condition is false, however, an AssertionError exception is thrown. You can include a message with the assertion, like this:
assert(condition, "Error: condition should be true")
If your assertion tests if the arguments of a method are correct, you should use require(condition) instead. require works exactly like assert, but throws an IllegalArgumentException if the condition is false.