流行编程语言的详细对比(5)--异常处理

异常处理
Java

try{
       System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
}
finally{
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
}
      

Js
JavaScript中的throw命令事实上可以抛出任何对象,并且我们可以在catch接受到此对象。例如:

try {
	    throw new Date(); // 抛出当前时间对象 
}catch (e) { 
	    alert(e.toLocaleString()); 
    // 使用本地格式显示当前时间
}

Python

try:
    fh = open("testfile", "w")
    try:
        fh.write("这是一个测试文件,用于测试异常!!")
    finally:
        print "关闭文件"
        fh.close()
except IOError:
    print "Error: 没有找到文件或读取文件失败"

Go
panic,recover
Panic是一个内建函数,可以中断原有的控制流程,进入一个令人恐慌的流程中。当函数F调用panic,函数F的执行被中断,但是F中的延迟函数会正常执行,然后F返回到调用它的地方。在调用的地方,F的行为就像调用了panic。这一过程继续向上,直到发生panic的goroutine中所有调用的函数返回,此时程序退出。恐慌可以直接调用panic产生。也可以由运行时错误产生,例如访问越界的数组。
Recover
是一个内建的函数,可以让进入令人恐慌的流程中的goroutine恢复过来。recover仅在延迟函数中有效。在正常的执行过程中,调用recover会返回nil,并且没有其它任何效果。如果当前的goroutine陷入恐慌,调用recover可以捕获到panic的输入值,并且恢复正常的执行。

下面这个函数演示了如何在过程中使用panic

var user = os.Getenv("USER")
func init() {
	if user == "" {
	panic("no value for $USER")
	}
}

下面这个函数检查作为其参数的函数在执行时是否会产生panic:

func throwsPanic(f func()) (b bool) {
	defer func() {
		if x := recover(); x != nil {
			b = true
		}
	}()

	f() //执行函数f,如果f中出现了panic,那么就可以恢复回来
	return
}

Scala

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

PHP

<?php
class customException extends Exception{
	public function errorMessage(){
		//error message
		$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
		return $errorMsg;
	}
}

$email = "someone@example.com";
try{
	//check if 
	if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
		//throw exception if email is not valid
		throw new customException($email);
	}
	//check for "example" in mail address
	if(strpos($email, "example") !== FALSE){
		throw new Exception("$email is an example e-mail");
	}
}
catch (customException $e){
	echo $e->errorMessage();
}
catch(Exception $e){
	echo $e->getMessage();
}
finally{
	echo "This is finally.\n";
}
?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值