Im writing a program that should read data from an online XML file. The computation is done by classes written in Scala, should any exception be caught, it must be thrown to a Java class that will handle the exceptions. For some reason, i get an error with the exception type. What is the right exception that should be thrown when trying to access a bad URL or any similar issue (no internet connection?). Thanks!
The main class (Scala)
object test
{
def main(args:Array[String])
{
val x:A = new A()
}
}
The class that parses the XML file and tries to access the URL
import java.net.{URL, URLConnection}
import xml.{XML, Elem}
import java.lang.NullPointerException
import java.io.IOException
class XMLparser {
@throws(classOf[Exception])
private val connectionXMLURL = "http://www.boi.org.il/currency.xml1"
private var urlConnection:URLConnection = null
private var url:URL = null
private var doc:Elem = null
private val currencies = new java.util.LinkedHashMap[String,java.lang.Double]()
try
{
url = new URL(connectionXMLURL)
urlConnection = url.openConnection
doc = XML.load(urlConnection.getInputStream)
}
catch
{
case ex: org.xml.sax.SAXParseException => //is caught!!! and thrown!
{
throw ex
}
case e: IOException =>
{
throw e
//add error log!!
}
case e: NullPointerException =>
{
throw e
//add error log!!
}
case e: Exception =>
{
throw e
}
}
}
The class that should catch the exception (Java)
public class A
{
private XMLparser x;
public A()
{
try
{
x = new XMLparser();
}
catch(org.xml.sax.SAXParseException e) //Cannot catch it!!??
{
}
/* catch (Exception e)
{
e.printStackTrace();
} */
}
}
EDIT: this is the error message i get when trying to catch the exception:
scala: warning: [options] bootstrap class path not set in conjunction with -source 1.6
scala: C:\Users\home\Dropbox\Exchange Currency\src\il\hit\currencyExchange\CurrencyExchangeGUI.java:138: error: exception SAXParseException is never thrown in body of corresponding try statement
scala: catch (org.xml.sax.SAXParseException ex)
The problem is that you need to declare that your constructor method (the default one) throws a checked java exception. I saw that you already added the
@throws(classOf[Exception])annotation to your code, but it is slightly misplaced for your purposes. Check this linkhttps://issues.scala-lang.org/browse/SI-1420
It should look like