Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional try & catch with Scala

Tags:

Is there a more idiomatic way of opening a resource in Scala and applying methods to it than this method (translated directly from java):

var is: FileInputStream = null try {   is = new FileInputStream(in)   func(is) } catch {   case e: IOException =>     println("Error: could not open file.")     println("       -> " + e)     exit(1) } finally {   if(is) is.close() } 
like image 493
Aaron Yodaiken Avatar asked Feb 28 '11 23:02

Aaron Yodaiken


People also ask

What is a try function?

The main purpose of try functions is to catch errors/exceptions that are thrown by Dynamics NAV or exceptions that are thrown during . NET Framework interoperability operations. Try functions catch errors similar to a conditional Codeunit.

What is functional error?

When dealing with errors in a purely functional way, we try as much as we can to avoid exceptions. Exceptions break referential transparency and lead to bugs when callers are unaware that they may happen until it's too late at runtime.

What is the purpose of try block?

Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.

What is finally in try-catch?

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.


2 Answers

The loan pattern is implemented in various ways in Josh Suereth's scala-arm library on github.

You can then use a resource like this:

val result = managed(new FileInputStream(in)).map(func(_)).opt  

which would return the result of func wrapped in an Option and take care of closing the input stream.

To deal with the possible exceptions when creating the resource, you can combine with the scala.util.control.Exception object:

import resource._ import util.control.Exception.allCatch  allCatch either {    managed(new FileInputStream(in)).map(func(_)).opt  } match {   case Left(exception) => println(exception)   case Right(Some(result)) => println(result)   case _ => } 
like image 52
huynhjl Avatar answered Sep 19 '22 06:09

huynhjl


Use the Loan pattern (dead link) non permanent link to new location.

like image 34
shellholic Avatar answered Sep 21 '22 06:09

shellholic