[scala] exception handling

Scala's exception handling is similar to other languages ​​such as Java.

Throw an exception

Scala throws exceptions in the same way as Java, using the throw method

throw new IllegalArgumentException

catch exception

The mechanism of catching exceptions in Scala is similar to that in Java. Exceptions are captured through try-catch, and catch captures exceptions in try blocks.

It should be noted that if an exception occurs, the catch clauses are captured in order. The more specific anomalies are placed in the front, the more general anomalies are placed in the back.

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch { // catch and handle exception
         case ex: FileNotFoundException =>{
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      }
   }
}

We noticed that the format case ex: Exception => ... is not a bit like the format of case in pattern matching.

In fact, catching exceptions is to borrow the idea of ​​pattern matching to do exception matching.

The content in the catch clause is exactly the same as the case in the match.

finally statement

As in Java, the finally statement is used to perform steps that need to be executed regardless of normal processing or when an exception occurs.

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch { // catch exception and handle it
         case ex: FileNotFoundException => println("Missing file exception")    
         case ex: IOException => println("IO Exception")     
      } finally { //will be executed
         println("Exiting finally...")
      }
   }
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324841815&siteId=291194637
Recommended