ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to create a custom exception

Here, we are going to learn how to create a custom exception in Scala programming language?
Submitted by Nidhi, on June 08, 2021

Problem Solution:

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

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.

Scala Exception Handling Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.