Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SCALA

Scala Exception Handling: Try, Catch and Throw

Handle exceptions with try, catch and throw. Use case to match exception types.
Try, exceptions. A program fails. A stack trace appears. But nothing further happens in the program. Exceptions happen often in development.
With exception handling, we trap and process these exceptions. Our programs can continue as though they were never stopped. In Scala we use keywords: try, catch, throw.
An example. This program uses a try-construct. Its division expression will cause an ArithmeticException to occur. The catch block is entered.
Scala program that handles exceptions try { // Try to perform an impossible operation. val mistake = 1 / 0 } catch { // Handle exceptions. case npe: NullPointerException => println("Result NPE: " + npe) case ae: ArithmeticException => println("Result AE: " + ae) } Output Result AE: java.lang.ArithmeticException: / by zero
Throw, Throwable. Here we use the throw keyword to create an exception. With the case, we catch all Throwables—so all exceptions are caught here.

Tip: In Scala we must specify the Throwable type for the case to avoid a compiler warning.

Scala program that uses throw, catches Throwable try { // Throw an Exception. throw new Exception("Failure") } catch { // Catch all Throwable exceptions. case _: Throwable => println("An exception was thrown") } Output An exception was thrown
Null, NullPointerException. The NullPointerException is common. It is caused when we try to access a field or method on a null variable. Here we see a Scala stack trace.
Scala program that causes NullPointerException // Print length of this string. var x = "cat" println(x.length) // Reassign string to null. // ... Now a NullPointerException is caused. x = null println(x.length) Output 3 java.lang.NullPointerException at Main$$anon$1.<init>(program.scala:10) at Main$.main(program.scala:1) at Main.main(program.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source)...
A review. With the try, catch and throw keywords, we implement basic exception handling in Scala. With cases, we match specific kinds of Throwable exceptions, like ArithmeticException.
The Dev Codes