65.scala编程思想笔记——用过异常进行错误处理

本文深入探讨了Scala编程中通过捕获和处理异常来优化错误报告的过程,包括自定义异常类和异常处理策略的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

65.scala编程思想笔记——用过异常进行错误处理

欢迎转载,转载请标明出处:http://blog.youkuaiyun.com/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"

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值