Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch in Java a exception thrown in Scala - unreachable catch block

Scala doesn't have checked exceptions. However, when calling scala code from java, it's desirable to catch exceptions thrown by scala.

Scala:

def f()=
    {
    //do something that throws SomeException
    }

Java:

try
    { f() }
catch (SomeException e)
    {}

javac doesn't like this, and complains that "this exception is never thrown from the try statement body"

Is there a way to make scala declare that it throws a checked exception?

like image 367
loopbackbee Avatar asked Nov 15 '13 17:11

loopbackbee


People also ask

How do I fix unreachable catch block error?

When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error.

What is unreachable catch block in Java?

An unreachable catch clause may indicate a logical mistake in the exception handling code or may simply be unnecessary. Although certain unreachable catch clauses cause a compiler error, there are also unreachable catch clauses that do not cause a compiler error.

What happens if an exception is thrown in catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

Can we throw an exception in catch block in Java?

The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.


1 Answers

Use a throws annotation:

@throws(classOf[SomeException])
def f()= {
    //do something that throws SomeException
    }

You can also annotate a class constructor:

class MyClass @throws(classOf[SomeException]) (arg1: Int) {
}

This is covered in the Tour of Scala

like image 126
loopbackbee Avatar answered Oct 24 '22 03:10

loopbackbee