Q:

Scala program to create a custom exception

belongs to collection: Scala Exception Handling Programs

0

Here, we will create a custom exception class by extending the Exception class and declared the method with the throws keyword.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create a custom exception is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a custom exception

class MyException(msg: String) extends Exception(msg) {}
class ExceptionEx {
  @throws(classOf[MyException])
  def divide(num1: Int, num2: Int) {
    var result: Int = 0;
    if (num1 == 0) {
      throw new MyException("Divide by 0")
    } else {
      result = (num2 / num1);
      printf("Result: %d\n", result);
    }
  }
}

object Sample {
  // Main method
  def main(args: Array[String]) {
    try {
      var obj = new ExceptionEx();
      obj.divide(0, 10);
    } catch {
      case e: MyException => println(e);
    } finally {
      println("Finally block executed")
    }
  }
}

Output:

MyException: Divide by 0
Finally block executed

Explanation:

Here, we created a MyException class by extending the Exception class and then created a class ExceptionEx class, that contains the divide() method, created with the throws keyword.

And, we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created object of ExceptionEx class and called divide() method. And, we also defined catch and finally blocks to handle generated exceptions and print appropriate messages on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to demonstrate the NumberFormatExcep... >>
<< Scala program to demonstrate the throws keyword...