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

这里写图片描述

猜你喜欢

转载自blog.csdn.net/ugghhj/article/details/84076811
65
今日推荐