1

我正在编写一个应该从在线 XML 文件中读取数据的程序。计算由用 Scala 编写的类完成,如果捕获到任何异常,则必须将其抛出到将处理异常的 Java 类。出于某种原因,我收到异常类型的错误。尝试访问错误的 URL 或任何类似问题(没有互联网连接?)时应该抛出的正确异常是什么。谢谢!

主类(Scala)

object test 
{
  def main(args:Array[String])
  {
    val  x:A =  new A()
  }

}

解析 XML 文件并尝试访问 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
      }      
    }

}

应该捕获异常的类(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();
        } */
    }


}

编辑:这是我尝试捕获异常时收到的错误消息:

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)
4

2 回答 2

2

问题是您需要声明您的构造方法(默认方法)会抛出一个已检查的 java 异常。我看到您已经在@throws(classOf[Exception])代码中添加了注释,但是出于您的目的,它稍微放错了位置。检查此链接 https://issues.scala-lang.org/browse/SI-1420

它应该看起来像

class XMLparser @throws(classOf[Exception]) {

      private val connectionXMLURL = "http://www.boi.org.il/currency.xml1"
      ...
于 2013-01-09T12:54:20.330 回答
1

对于URLConnection,它可以SocketTimeoutException用于连接和输入流超时。它也可以是IOException一个不可用的网站。您可以在javadoc 中找到它URLConnection

于 2013-01-09T13:03:41.113 回答