Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
In Scala, the throw
keyword is used to raise or throw exceptions, similar to its usage in many other programming languages. Throwing an exception means signaling the runtime that an abnormal condition has occurred. This stops the normal flow of the program, and the runtime starts searching for the nearest catch clause that can handle the exception.
You can use the throw
keyword followed by an exception object:
def validateAge(age: Int): Unit = { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative!") } }
When the function is called with a negative age, it will throw an IllegalArgumentException
.
You can use a try-catch-finally block to catch and handle exceptions:
try { validateAge(-5) } catch { case e: IllegalArgumentException => println(e.getMessage) case _: Exception => println("An unknown error occurred.") } finally { println("This always runs, whether an exception was thrown or not.") }
In this example, the "Age cannot be negative!" message will be printed, followed by "This always runs, whether an exception was thrown or not."
In Scala, the try
-catch
-finally
construct is an expression, meaning it returns a value. You can assign the result of this expression to a variable.
Scala's catch
clause uses pattern matching. This makes it flexible to catch and handle multiple types of exceptions in different ways.
While it's possible to throw exceptions, it's idiomatic in many functional programming scenarios to avoid them for error handling. Instead, consider using types like Option
, Either
, or other monads that can represent failure without throwing exceptions.
Scala throw keyword example:
throw
keyword in Scala is used to explicitly throw an exception. It interrupts the normal flow of execution and transfers control to an exception handler.// Example using throw keyword val divisor = 0 try { if (divisor == 0) { throw new ArithmeticException("Division by zero") } val result = 10 / divisor println(s"Result: $result") } catch { case ex: ArithmeticException => println(s"Exception: ${ex.getMessage}") }
Exception handling with throw in Scala:
throw
involves throwing an exception in response to a specific condition and catching it in an appropriate exception handler.// Exception handling with throw val age = -5 try { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative") } println(s"Age: $age") } catch { case ex: IllegalArgumentException => println(s"Exception: ${ex.getMessage}") }
How to use throw in Scala for custom exceptions:
Exception
class, and instances of these exceptions can be thrown using the throw
keyword.// Custom exception class CustomException(message: String) extends Exception(message) // Throwing custom exception try { throw new CustomException("This is a custom exception") } catch { case ex: CustomException => println(s"Custom Exception: ${ex.getMessage}") }
Scala throw vs throw new:
throw
and throw new
are used to throw exceptions in Scala. throw new
is commonly used to instantiate and throw exceptions, while throw
is used to throw existing exceptions or errors.// Using throw new try { throw new RuntimeException("This is an exception") } catch { case ex: RuntimeException => println(s"Exception: ${ex.getMessage}") } // Using throw try { throw new IllegalArgumentException("Invalid argument") } catch { case ex: IllegalArgumentException => println(s"Exception: ${ex.getMessage}") }
Handling checked exceptions with throw in Scala:
Exception
) can be thrown and caught using the throw
keyword in Scala.// Handling checked exception with throw def riskyOperation(): Unit = { throw new IOException("File not found") } try { riskyOperation() } catch { case ex: IOException => println(s"IOException: ${ex.getMessage}") }
Throwing multiple exceptions in Scala:
def processInput(input: String): Unit = { if (input == null) { throw new NullPointerException("Input cannot be null") } else if (input.isEmpty) { throw new IllegalArgumentException("Input cannot be empty") } else { println(s"Processing input: $input") } } try { processInput(null) } catch { case ex: NullPointerException => println(s"NullPointerException: ${ex.getMessage}") case ex: IllegalArgumentException => println(s"IllegalArgumentException: ${ex.getMessage}") }
Throwing non-fatal exceptions in Scala:
RuntimeException
, can be thrown using throw
. These exceptions do not require explicit handling.// Throwing non-fatal exception try { throw new RuntimeException("This is a non-fatal exception") } catch { case ex: RuntimeException => println(s"Non-fatal Exception: ${ex.getMessage}") }