Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

multiple independent if statements within a try block

Posts: 6
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can i have multiple independent if statements within a try block with only one catch statement in order to set a value?

From my understanding if statement 1 throws an exception then the value of x could never be set through statement 2 and 3 so would it be better if i use if-elseif statements or is there a better solution to achieve this?
Posts: 2407
Scala Python Oracle Postgres Database Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are trying to write Scala as if it was Java, but Scala gives you different ways to do things.

You can use match/case to test multiple possibilities in Scala, so you don't need multiple "if" statements. Incidentally, remember that in Scala "if" is an expression that can be evaluated to return a value (like a function).

You should avoid exceptions in Scala if possible. Of course, sometimes they are necessary, in which case you will need to handle them properly. But you should not use them simply as branching logic, as you seem to be doing here. For example, one common alternative is to return an Option from your function and allow the calling function to handle the result i.e. Some(value) or None gracefully without the need for an exception.

There are several books and websites around to help Java programmers make the transition to Scala more easily, so here are a few places for you to start your Scala journey:

Scala tutorial for Java programmers
Learning Scala
Atomic Scala
Twitter Scala School
Scala Cookbook

You had your fun. Now it's time to go to jail. Thanks for your help tiny ad.
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic