PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to "override" an exception in scala?

 August 05, 2022     error-handling, exception, scala     No comments   

Issue

so I have a method which already has a try block that throws ExceptionA. Now I need to put another try block where this method is being called and needs to throw an exception with some added details. Something like this:

method inner():
    try{
    //some logic
    } catch {
    throw new ExceptionA("exceptionA occurred")
    }

method outer():
    identifier = fromSomeDBCallPrivateToOuter()
    try{
    inner()
    } catch {
    // now either 
    // throw new Exception("Error with identifier" + identifier)
    // or
    // append identifier to thrown error from inner() 
    }

Can someone please provide any insight or suggestion on how to do this in Scala? Thanks in advance!


Solution

What you have in your snippet would work as written (if you correct the syntax), with a caveat, that exceptions are immutable (and even they weren't, it's still not a good idea to mutate them), so, instead of "appending" to exception, you'd need to create a new one, and set the original as cause.

It is more idiomatic in scala though to use Try monad instead of the "procedural" try/catch blocks. Something like this:

     case class ExceptionB(id: String, original: ExceptionA) 
         extends Exception(s"Badness happened with id $id", original)
     def outer(): Try[ReturnType] = 
       val id = getId()
       Try {
         inner 
       } recover { 
         case e: ExceptionA if iWannaNewException => throw new Exception(s"Id: id")
         case e: ExceptionA => throw ExceptionB(id, e)
      }


Answered By - Dima
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing