JAVA学习19.异常
0.基础知识
异常:程序发生不正常的行为或出现不正常的状态
异常分类:1.Exception(程序相关)和2.Error(系统相关),这两个类都是Throwable的子类
Exception类是所有异常的父类。
Exception分类:
Unchecked Exception :!!!
(编译器不会辅助检查的,需要程序员自己管的)异常。编译过程中不会被编译器检查出来。包括Error子和RuntimeException子类。
Checked Exception
在编译的时候编译器就会进行检查,如果不解决完这种异常,程序无法运行
Error的子类
系统内部错误或者资源耗尽。可以不用处理
Throwable
所有错误的祖先
JAVA异常结构图
1.异常处理
异常处理的作用:
允许用户及时保存结果
抓住异常,分析异常内容
控制程序返回到安全状态
2.try catch finally
try-catch-finally: 一种保护代码正常运行的机制。
异常结构
try必须有,catch和finally至少要有一个
try…catch(catch可以有多个,下同)
try…catch…finally
try…finally
各个关键字的功能
try: 正常业务逻辑代码。
catch: 当try发生异常,将执行catch代码。若无异常,绕之。(多个catch块时从上到下进行匹配)(chatch处理之后不会返回try)
finally: 当try或catch执行结束后,必须要执行finally。(即使catch也有异常也是)
eg
public class TryDemo {
public static void main(String[] args) {
try
{
int a = 5/2; //无异常
System.out.println("a is " + a);
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
System.out.println("Phrase 1 is over");
}
try
{
int a = 5/0; //ArithmeticException
System.out.println("a is " + a);
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
System.out.println("Phrase 2 is over");
}
try
{
int a = 5/0; //ArithmeticException
System.out.println("a is " + a);
}
catch(Exception ex)
{
ex.printStackTrace();
int a = 5/0; //ArithmeticException
}
finally
{
System.out.println("Phrase 3 is over");
}
}
}
3.throws
throws功能:方法存在可能异常的语句,但不处理,那么可以使用throws来声明异常(遇到异常的时候才会出现)
调用带有throws异常(checked exception)的方法,要么处理这些异常,或者再次向外throws,直到main函数为止。
子类重写的方法所声明的异常不能超出父类方法声明的范围
public class ThrowsDemo
{
public static void main(String [] args)
{
try
{
int result = new Test().divide( 3, 1 );
System.out.println("the 1st result is" + result );
}
catch(ArithmeticException ex)
{
ex.printStackTrace();
}
int result = new Test().divide( 3, 0 );
System.out.println("the 2nd result is" + result );
}
}
class Test
{
//ArithmeticException is a RuntimeException, not checked exception
public int divide(int x, int y) throws ArithmeticException
{
int result = x/y;
return x/y;
}
}
4.自定义异常
public class MyException extends Exception {
private String returnCode ; //异常对应的返回码
private String returnMsg; //异常对应的描述信息
public MyException() {
super();
}
public MyException(String returnMsg) {
super(returnMsg);
this.returnMsg = returnMsg;
}
public MyException(String returnCode, String returnMsg) {
super();
this.returnCode = returnCode;
this.returnMsg = returnMsg;
}
public String getReturnCode() {
return returnCode;
}
public String getreturnMsg() {
return returnMsg;
}
}
public class MyExceptionTest {
public static void testException() throws MyException {
throw new MyException("10001", "The reason of myException");
}
public static void main(String[] args) {
//MyExceptionTest.testException();
try {
MyExceptionTest.testException();
} catch (MyException e) {
e.printStackTrace();
System.out.println("returnCode:"+e.getReturnCode());
System.out.println("returnMsg:"+e.getreturnMsg());
}
}
}