简体   繁体   中英

problems in default constructor with try/catch block

I wrote a program with Scala. In a default constructor I have these lines.

private val url = new URL("http://www.  **  .xml")   //  throws  UnknownHostException
private val conn = url.openConnection
private val doc = XML.load(conn.getInputStream)

As you know if you have Internet communication problems may be thrown Exception.

I tried several ways to write these lines in try/catch block . But every time it shows me other compilation errors elsewhere in the class, in places where I use these variables.

Of course I wrote them inside a block, I defined the variables as public.

Can someone write me an example of how to do it correctly?

I might not be specific enough, but I did not know what exactly to explain because I do not know where exactly is the problem.

Using pattern matching for the try/catch block is the idiomatic way to approach this in Scala.

import java.net.URL
import java.net._
import scala.xml.XML
try{
  val url = new URL("http://www. ** .xml")
  val conn = url.openConnection 
  val doc = XML.load(conn.getInputStream)
}catch{
  case uhe:UnknownHostException => println(uhe)
}

This might be an improvement:

import java.net.URL
import java.net._
import scala.xml.XML

val doc =
  try {
    val url = new URL("http://www.xxx.yyy/XYZZY.xml")
    val conn = url.openConnection
    Right(XML.load(conn.getInputStream))
  }
  catch {
    case ex: Exception => Left(ex)
  }

doc match {
  case Right(xmlDoc) => // Do stuff with the doc XML
  case Left(ex)      => // Do error stuff with the exception
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM