Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Scala's "try" mean without either a catch or finally block?

Tags:

scala

Unlike Java, Scala lets you do a bare "try", without either a catch or finally clause:

scala> try { println("Foo") } Foo 

Does this actually have any meaning beyond,

{ println("Foo") } 

?

like image 294
Matt R Avatar asked Oct 10 '09 09:10

Matt R


People also ask

Is try block without finally and catch allowed?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

What is the use of try and finally without catch?

@barth When there's no catch block the exception thrown in finally will be executed before any exception in the try block. So If there are two exceptions one in try and one in finally the only exception that will be thrown is the one in finally .

What is a try catch finally block?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.

How try catch and finally block works?

Syntax. The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.


1 Answers

Scala's exception handling works by passing any exceptions to an anonymous catch function. The catch function works by pattern matching the caught exception and, if it doesn't match it will pass the exception up.

The catch function is optional, if it's omitted then the exception is passed straight up. So essentially

try { exceptionThrowingFunction() } 

is the same as

exceptionThrowingFunction() 

See chapter 6.22 of the language spec pdf for more information.

like image 125
Dan Midwood Avatar answered Oct 01 '22 01:10

Dan Midwood