Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw Custom Exception

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.

like image 218
Echo Avatar asked Jul 16 '11 10:07

Echo


People also ask

Can we Throws custom exception?

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.

How do you throw your own exception?

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.

How do you throw a custom exception in C++?

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.


1 Answers

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") 
like image 85
paradigmatic Avatar answered Oct 24 '22 19:10

paradigmatic