您的位置:首页 > 编程语言

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

2017-08-19 14:53 232 查看
异常处理

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";
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: