文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Java PHP Go Lua 异常处理【原创】  



下载PDF: houhuiyang-118502874-241217-1212-15822.pdf(133 KB)

一:概述:

Java在书写函数抛出可预知异常,就会向上抛,使用该函数的必须使用 try 不使用就会报错,例如: Unhandled exception type

AgeException;

PHP和Python 都没有throws的概念,这样就要求程序员一定要注意使用未知函数的安全性;

Go没有采用Try...catch 这种处理方式,而是采用“延迟处理”的方式;

Lua 是利用C来操作虚拟机,Lua虚拟机是C在堆上的内存对象,Lua的做法是由异常交给用户来处理;

PHP的常见使用错误方式是在函数里面使用了throw new exception 但是使用函数的代码没有用try...catch接住;


二:分语言介绍

1:PHP & Python & Lua

错误

PHP&Python&Lua

语法错误

PHP

常见错误

Deprecated 最低级别的错误

Notice 通知级别的错误

Warning 警告级别的错误

Fatal error 致命级错误

Parse error 语法解析错误

E_USER_相关的错误

设置错误级别

通过PHP.ini error_reporting设置

在代码中直接使用error_reporting(-1);

在代码中使用init_set设置

其他

通过set_error_handler来接管PHP的错误

register_shutdown_function PHP在意外死掉前执行的遗言

Python

变量未定义【NameError: name 'a' is not defined】

语法错误,不会真正执行代码【SyntaxError: invalid syntax】

输入、输出错误【IOError】

除数为0【ZeroError】

类型转换错误【valueError】

对类型无效的操作【TypeError】

字典中查找不存在的键【KeyError】

序列中没有此索引【IndexError】

导入模块/对象失败【ImportError】

人为终止程序运行【KeyboardInterrupt】

Lua

'do' expected near 【语法错误】

环境错误

配置问题、版本问题

逻辑错误

异常处理

PHP

try {...} catch {...} //catch 可以有多个 注意 throw 的配合使用

try {...} catch {...} finally {...}

Python

try: ... except: ...

try: ... except: ... else: ...

try: ... except ... finally: ...

raise

with open as ...

Lua

error

pcall

xpacall

debug

断言

PHP

Python

Lua


// 错误处理

<?php

// php5.5

// 程序会继续运行

// Deprecated: Function ereg() is deprecated in xxx

if (ereg("didi", "hello didi", $aMatch)) {

print_r($aMatch);

}

//// Notice: Undefined variable: aData in

print_r($aData);

// Warning: settype(): Invalid type in

$iOrderId = "111111";

settype($iOrderId, "integer");

settype($iOrderId, "didi");

// 程序会中止运行

// PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function getOrderInfo()

function getOrderInfo($iOrderId) {

return false;

}

getOrderInfo();

// PHP Parse error: syntax error, unexpected end of file, expecting

print_r($_COOKIE)



>>> print(a)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

>>> if True

File "<stdin>", line 1

if True

^

SyntaxError: invalid syntax

>>> a = "11a"

>>> print(int(a))

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '11a'



// 异常处理

<?php

try {

$iNum1 = 8;

$iNum2 = 0;

$iNum3 = $iNum1 % $iNum2;

var_dump($iNum3);

} catch (DivisionByZeroError $e) {

var_dump($e->getMessage() . "---" . $e->getFile());

} finally {

echo "执行完毕1...\n";

}

try {

$iNum11 = 8;

$iNum22 = 0;

if ($iNum22 == 0) {

throw new Exception("0不能是除数...");

}

$iNum33 = $iNum11 / $iNum22;

var_dump($iNum33);

} catch (Exception $e) {

$aError = array(

"file" => $e->getFile(),

"line" => $e->getLine(),

"msg" => $e->getMessage()

);

var_dump($aError);

} finally {

echo "执行完毕2...\n";

}


#!/usr/bin/env python3

# -*- coding: utf-8 -*-

try:

print('try...')

r = 10 / 0

print('result:', r)

except ZeroDivisionError as e:

print('except:', e)

finally:

print('finally...')

print('END')

print("###############")

try:

f = open("1.txt", "r")

line = f.read(2)

print(line)

except IOError as e:

print("io: %s" % e)

else:

print("no.....")

print("###############")

class FileError(IOError):

pass

try:

raise FileError, "Test FileError"

except FileError as e:

print e

print("###############")

with open("2.txt", "r") as f:

lines = f.readlines()

print(lines)



> pcall(function(i) print(i) end, 'didi')

didi

true

> pcall(function(i) print(i) error('error..') end, 'didi')

didi

false stdin:1: error..

> xpcall(function(i) print(i) error('error..') end, function() print(debug.traceback()) end, 'didi')

didi

stack traceback:

stdin:1: in function <stdin:1>

[C]: in function 'error'

stdin:1: in function <stdin:1>

[C]: in function 'xpcall'

stdin:1: in main chunk

[C]: in ?

false nil


// php

assert_options(ASSERT_ACTIVE, 1);

assert_options(ASSERT_WARNING, 0);

assert_options(ASSERT_QUIET_EVAL, 1);

$a = "abc";

var_dump(assert("is_int($a)"));

// python

def foo(s):

n = int(s)

assert n != 0, 'n is zero!'

return 10 / n

def main():

foo('0')

main()

// lua

assert(type(10) == "number")



2:Java

Throwable java.lang.Throwable

错误 java.lang.Error

VirtualMachineError

AWTError

异常处理 java.lang.Exception

RuntimeException

IOException

ClassNotFoundException

ClassNotSupportException

try {...} catch {...} finally {...}

throw throws

自定义异常


package tryTest;

public class Test2 {

public static void main(String[] args) {

// Jvm 可以自动捕捉异常

// try {

// System.out.println(args[0]);

// } catch (ArrayIndexOutOfBoundsException e) {

// System.out.println("数组下标越界");

// }

//

try {

int a = Integer.parseInt(args[0]);

int b = Integer.parseInt(args[1]);

System.out.println(a / b);

} /*catch(ArrayIndexOutOfBoundsException e) {

System.out.println("数组下标越界");

} catch(ArithmeticException e) {

System.out.println("除数不能为0");

} */catch(Exception e) {

StackTraceElement stackTraceElement[] = e.getStackTrace();

for (int i = 0; i < stackTraceElement.length; i++) {

StackTraceElement anyException = stackTraceElement[i];

String className = anyException.getClassName();

String methodName = anyException.getMethodName();

String fileName = anyException.getFileName();

int lineNumber = anyException.getLineNumber();

System.out.println("StackTraceElement数组下标 i=" + i + ",fileName="

+ fileName + ",className=" + className + ",methodName="

+ methodName + ",lineNumber=" + lineNumber);

}

System.out.println("############################");

System.out.println(e.toString()); //java.lang.ArithmeticException: / by zero

} finally {

System.out.println("关闭资源");

}

}

}

package tryTest;

public class Test7 {

public static void main(String[] args) {

PersonB b = new PersonB();

try {

b.setAge(100);

System.out.println(b.getAge());

} catch (AgeException e) {

e.printStackTrace();

}

}

}

class PersonB {

private int age;

public void setAge(int age) throws AgeException {

if (age < 0 || age > 120) {

throw new AgeException("年龄不对");

}

this.age = age;

}

public int getAge() {

return age;

}

}

package tryTest;

public class AgeException extends Exception {

public AgeException(String message) {

super(message);

}

}




3:Go

错误

error

异常处理

panic

defer

recover



package main

import (

"errors"

"fmt"

)

type MyError struct {

Num int

}

func (e MyError) Error() string {

return fmt.Sprintf(" %d, > 55", e.Num)

}

func Equal(n int) (int, error) {

if n > 55 {

return -1, errors.New("> 55")

}

return n, nil

}

func DiyEqual(n int) (int, error) {

if n > 55 {

return -1, MyError{Num: n}

}

return n, nil

}

func f() {

panic(550000)

}

func main() {

// errors.New

if result, err := Equal(100); err != nil {

fmt.Println("错误:", err)

} else {

fmt.Println("结果:", result)

}

// MyError

if result, err := DiyEqual(100); err != nil {

fmt.Println("错误:", err)

} else {

fmt.Println("结果:", result)

}

// defer

for i := 0; i < 5; i++ {

defer fmt.Printf("%d ", i)

}

// recover

defer func() {

fmt.Println("test recover...")

if r := recover(); r != nil {

fmt.Printf("Recovered! Panic message[%s]\n", r)

}

}()

f()

}