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?
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.
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.
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.
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.
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
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