scala exceptions and IO

exception handling

The syntax is similar to Java, but not the same.

java exception handling

public class ExceptionDemo {
 public static void main(String[] args) {
 try {
 int a = 10;
 int b = 0;
 int c = a / b;
 }catch (ArithmeticException e){
// catch 时,需要将范围小的写到前面
 e.printStackTrace();
 }catch (Exception e){
 e.printStackTrace();
 }finally {
 System.out.println("finally");
 }
 } 
}

Notes
(1) The Java language handles exceptions in a try-catch-finally manner
(2) finally will be executed regardless of whether there is an exception caught or not, so resources can usually be released in the finally code block.
(3) There can be multiple catches to catch the corresponding exceptions respectively. At this time, it is necessary to write the exception class with a small range in front, and write the exception class with a large range in the back, otherwise the compilation error will occur.

Scala exception handling

def main(args: Array[String]): Unit = {
 try {
 var n= 10 / 0
 }catch {
 case ex: ArithmeticException=>{
 // 发生算术异常
 println("发生算术异常")
 }
 case ex: Exception=>{
 // 对异常处理
 println("发生了异常 1")
 println("发生了异常 2")
 }
 }finally {
 println("finally")
 } 
}

Summary:
We encapsulate the suspicious code in a try block. A catch handler is used after the try block to catch the exception. If any exception occurs, the catch handler will handle it and the program will not terminate abnormally.

Scala's exception working mechanism is the same as Java's, but Scala does not have "checked (compile time)" exceptions, that is, Scala does not have the concept of compilation exceptions, and exceptions are caught and processed at runtime.

The mechanism of exception catching is the same as in other languages. If an exception occurs, the catch clauses are caught in order. Therefore, in the catch clause, the more specific exceptions should be placed earlier, and the more common exceptions should be placed later. If you write the more common exceptions first and the specific exceptions last, no error will be reported in Scala , but this is very bad programming style.

The finally clause is used to perform steps that need to be performed whether it is normal processing or when an exception occurs. It is generally used for object cleanup, which is the same as Java.

With the throw keyword, an exception object is thrown. All exceptions are subtypes of Throwable. Throw expressions are typed, that is, Nothing, because Nothing is a subtype of all types, so throw expressions can be used where types are required

def test():Nothing = {
 throw new Exception("不对")
}
// java 提供了 throws 关键字来声明异常。
// 可以使用方法定义声明异常。
// 它向调用者函数提供了此方法可能引发此异常的信息。
// 它有助于调用函数处理并将该代码包含在 try-catch块中,以避免程序异常终止。
// 在 Scala 中,可以使用 throws 注解来声明异常
Scala
def main(args: Array[String]): Unit = {
 f11()
}
@throws(classOf[NumberFormatException])
def f11()={
 "abc".toInt
} 

IO

enter

Source.fromFile()

input line

/**
  * 2019/11/18
  * @author Hangge.z  WX:17710299606
  */
object LineIO {
  def main(args: Array[String]): Unit = {
   // 读取文件
    val bs: BufferedSource = Source.fromFile("d://data.txt")
    // 获取所有的行
    val lines: Iterator[String] = bs.getLines()
    // 遍历所有的行
    for (line <- lines) {
      println(line)
    }
    // 行列表
    val list: List[String] = lines.toList
    //行数组
    val array: Array[String] = lines.toArray
    // 整个字符串
    val content: String = lines.mkString
    // 释放资源
    bs.close()
  }
}

input bytes

/**
  * 2019/11/18
  * @author Hangge.z  WX:17710299606
  *
  */
object ByteIo {
  def main(args: Array[String]): Unit = {
    val bs: BufferedSource = Source.fromFile("d://data.txt")
    // 获取输入流对象
    val reader: InputStreamReader = bs.reader()
    //跳过指定长度  到指定位置
    reader.skip(1)
    // 读取一个字节 
    val byte: Int = reader.read()
    println(byte) // 99
    reader.close()
    bs.close()
  }
}
def main(args:Array[String]):Unit={
  val file = new File("F:\\info.bin")
  val in = new FileInputStream(file)
  val bytes = new Array[Byte](file.length.toInt)
  in.read(bytes)
  in.close

read other data sources

//从URL读取
val source= Source.fromURL("http://www.baidu.com","UTF-8")
val lineIterator =source.getLines
for(l<-lineIterator){
  println(l.toString())
}
//从给定的字符串读取--调试有用
val source2= Source.fromString("Hello DOIT")
println(source2.mkString)//Hello DOIT
//从标准输入读取
val in: BufferedReader = Console.in
println(in.readLine())

output

def main(args: Array[String]): Unit = {
  val out = new PrintWriter("F:\\aa.txt")
  for(i<-1 to 100)
    out.println(i)
p.write("")
p.write(Array[Char]('a'))
p.append("")
  out.close
}

Guess you like

Origin blog.csdn.net/qq_61162288/article/details/131564075