Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: How to know the program have unhandled exceptions before running?

Tags:

scala

this is a test program:

object Test {

    def main(args: Array[String]): Unit = {
        // there is an unhandled exception in here, I expect program can remind me, and I can handled it before running.
        myException()  
    }

    def myException: Unit ={
        throw new Exception
    }
}

In Java, when I called a method with unhandling exception, the program will occur error, and tell you add throws declaration or surround with try/catch.

How to know the program have unhandled exceptions before running in Scala?

like image 769
Guo Avatar asked Mar 06 '17 07:03

Guo


People also ask

How do you find the unhandled exception?

If your application has unhandled exceptions, that may be logged in the Windows Event Viewer under the category of “Application”. This can be helpful if you can't figure out why your application suddenly crashes. Windows Event Viewer may log 2 different entries for the same exception.

How do you handle exceptions in Scala?

try/catch/finally A basic way we can handle exceptions in Scala is the try/catch/finally construct, really similar to the Java one. In the following example, to make testing easier, we'll return a different negative error code for each exception caught: def tryCatch(a: Int, b: Int): Int = { try { return Calculator.

Why does Scala have no checked exceptions?

However, unlike Java, Scala has no “checked” exceptions—you never have to declare that a function or method might throw an exception. In Java, “checked” exceptions are checked at compile time. If your method might throw an IOException, you must declare it.

Which event is used for unhandled exceptions?

The UnhandledException event is raised for unhandled exceptions thrown in other threads.


1 Answers

Scala has a somewhat different philosophy with regards to Exceptions.

The rule of thumb is to not use them unless for something truly exceptional and, thus "let it fail". The reason invoked behind this rule is that, in FP terms, exceptions break referential transparency.

The good practice is to use Either or Option to handle/wrap "errors" rather than throwing exceptions. (the link provided by @Tawkir seems a good read)

Unfortunately this does not help when interfacing with Java code which often uses Exceptions for program control flow, and the compiler will not help you there. A practical way around this is to wrap Exception throwing code with a Try and then call recover or recoverWith to handle these exceptions and, say, wrap them in another structure.

Please note that you can mark a scala method with an @throws annotation to specify the Exception(s) that this method throws, but this should really be used when writing scala code meant to be used by a Java caller expecting an Exception to be thrown.

like image 59
Bruno Grieder Avatar answered Sep 21 '22 23:09

Bruno Grieder