I am trying to avoid variable variables, but the problem is that I have to access the val that I need to initialize inside try (this is a db operation that is executed using migth) and I need this var in the finally block
I tried several alternatives:
Val declaration inside try block
try {
val resultSet = SQL(sql).resultSet
return ColumnInfo(resultSet.getMetaData)
} catch {
case e => throw new ColumnInfoException("Error getting metadata")
} finally {
resultSet.close
}
error: not found: value resultSet
Declaring a val value outside a try block without initialization
val resultSet: java.sql.ResultSet
try {
resultSet = SQL(sql).resultSet
return ColumnInfo(resultSet.getMetaData)
} catch {
case e => throw new ColumnInfoException("Error getting metadata")
} finally {
resultSet.close
}
error: only classes can have declared but undefined members
using var that seems to work
var resultSet: java.sql.ResultSet = null
try {
resultSet = SQL(sql).resultSet
return ColumnInfo(resultSet.getMetaData)
} catch {
case e => throw new ColumnInfoException("Error getting metadata")
} finally {
resultSet.close
}
and finally a nested try-catch block that seems pretty dirty
try {
val resultSet = SQL(sql).resultSet
try {
return ColumnInfo(resultSet.getMetaData)
} catch {
case e => throw new ColumnInfoException("Error getting metadata")
} finally {
resultSet.close
}
} catch {
case e => throw new ColumnInfoException("Error opening resultSet")
}
Is there any better approach I can take to avoid using vars and blocking try-catch nesting?
source
share