scala

Scala custom exception handling

Scala custom exception handling 

If you are creating your own Exception that is known as custom exception or user-defined exception. Scala custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let’s see a simple example of Scala custom exception handling

import java.io.IOException

class invalidageexcepton(smth: String) extends Exception(smth) {

}
object testexe {

  def validate(age: Int) {
    if (age < 18) {
      throw new invalidageexcepton("notvalid")
    } else {
      println("welcome to vote")

    }
  }
  def main(args: Array[String]) {
    try {
      validate(13)
    } catch {
      case ex: Exception => {
        println("output:" + ex)
      }
    }
  }
}

Output

output:invalidageexcepton: notvalid