1. 程式人生 > >65 scala程式設計思想筆記——用過異常進行錯誤處理

65 scala程式設計思想筆記——用過異常進行錯誤處理

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

65.scala程式設計思想筆記——用過異常進行錯誤處理

歡迎轉載,轉載請標明出處:http://blog.csdn.net/notbaron/article/details/50458746
原始碼下載連線請見第一篇筆記。

改進錯誤報告機制是提高程式碼可靠性的最強有力的方式之一。

         捕獲錯誤的理想時機是在SCALA執行程式之前對程式進行分析的時候。

         處理錯誤沒有明確的唯一解決方案,錯誤處理這個話題在不斷的演化。

         異常是從錯誤發生地點 “丟擲”的物件,物件可以被匹配其錯誤型別的恰當的異常處理器捕獲。

例如:

import com.atomicscala.AtomicTest._

 

class Problem(val msg:String)

  extendsException

 

def f(i:Int) =

  if(i == 0)

    throw newProblem("Divide by zero")

  else

    24/i

 

def test(n:Int) =

  try {

    f(n)

  } catch {

    caseerr:Problem =>

     s"Failed: ${err.msg}"

  }

 

test(4) is 6

test(5) is 4 // Integer truncation

test(6) is 4

test(0) is "Failed: Divide by zero"

test(24) is 1

test(25) is 0 // Also truncation

scala從JAVA繼承了許多不同的異常型別,幾乎沒有定義自己的異常型別。可以通過繼承Exception類來定義定製的異常。

         方法經常會產生不止一種型別的異常,即會因多種原因失敗,為了複用,可以封裝在一個package 中,如下:

package errors

 

case class Except1(why:String)

  extendsException(why)

case class Except2(n:Int)

  extendsException(n.toString)

case class Except3(msg:String, d:Double)

  extendsException(s"$msg $d")

 

object toss {

  defapply(which:Int) =

    which match{

      case 1=> throw Except1("Reason")

      case 2 => throw Except2(11)

      case 3=>

        throwExcept3("Wanted:", 1.618)

      case _=> "OK"

    }

}

被其他程式使用如下:

import com.atomicscala.AtomicTest._

import errors._

 

def test(which:Int) =

  try {

    toss(which)

  } catch {

    caseExcept1(why) => s"Except1 $why"

    caseExcept2(n) => s"Except2 $n"

    caseExcept3(msg, d) =>

     s"Except3 $msg $d"

  }

 

test(0) is "OK"

test(1) is "Except1 Reason"

test(2) is "Except2 11"

test(3) is "Except3 Wanted: 1.618"

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述