Search code examples
scalaexception

Custom Exception in scala


how can i create custom exceptions in Scala extending Exception class and throw them when exception occurs as well as catch them.

example in java :

class CustomException extends Exception {

  public final static String _FAIL_TO_INSERT = "FAIL_TO_INSERT";

}

Solution

  • final case class CustomException(private val message: String = "", 
                               private val cause: Throwable = None.orNull)
                          extends Exception(message, cause) 
    

    Just try catch:

    try {
        throw CustomException("optional")
    } catch {
        case c: CustomException =>
              c.printStackTrace
    }