Is using Try[Unit] the proper way?

给你一囗甜甜゛ 提交于 2019-12-09 02:36:57

问题


I recently came across the concept of Try/Success/Failure, and I am wondering how to use it for a method that has the return type Unit. Is using Try[Unit] the correct way? Maybe I am too influenced from my Java background, but is it a good idea to force the caller to deal with the problem?


回答1:


Try[Unit] is normal. For example, if you persist the entity, you can use:

try { 
    em.persist(entity)
} catch{
  case ex:PersistenceException =>
  handle(ex)
} 

or just

Try(em.persist(entity)) match {
  case Success(_) => 
  case Failure(ex) => handle(ex)
}


来源:https://stackoverflow.com/questions/23898507/is-using-tryunit-the-proper-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!