I'm trying to throw a custom exception.
The implementation of the custom exception class is:
case class customException(smth:String) extends Exception
In my code I wrapped a piece of code that I'm sure throws throw an exception with try/catch to throw my customException.
try{ val stateCapitals = Map( "Alabama" -> "Montgomery", "Alaska" -> "Juneau", "Wyoming" -> "Cheyenne") println("Alabama: " + stateCapitals.get("AlabamaA").get) } catch{ case x:Exception=>throw classOf[CustomException] }
I got a compilation error that says :
found : java.lang.Class[CustomException] [INFO] required: java.lang.Throwable [INFO] case x:Exception=>throw classOf[CustomException]
How could I throw my own custom exception on this case? Later I'm checking if the thrown exception is of a type[x] to do something specific.
In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
In the main() function, a try-catch block is created to throw and handle the exception. Within the try block, an object of MyCustomException is created and thrown using the throw keyword. The exception is then caught in the catch block, where the message is printed by accessing the what() function.
You're not throwing an exception, but the class of an exception (just read the compiler error message...). You have to throw an exception instance.
case x:Exception => throw new CustomException("whatever")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With