异常处理机制:
Java异常定义:是对程序在运行过程中出现错误进行处理的一种机制。
1.如果不是runtimeException(uncheckException),即普通的异常,编译都通不过,否则是(runtimeException)可以通过编译!,但是运行不过。
2.//注意,如果将大的异常(Exception)写在小的异常(FileNotFoundException)上边的话,就会出现CHECK eXCEPTION异常,即编译都通不过!
3.异常都继承自:throwable(1.exception2.runtimeException)
4.一般有throw就必须有throws(如果throw的是runtimeException的话,可以不写throws,其他的都需写.)
5.如果是你在方法中写了throw语句,哪么你就必须在调用该方法的方法中将此异常捕获,(runtimeException异常可以捕获也可以不捕获)。如果是runtimeException不捕获的话,那就交给java虚拟机去进行处理了.
public class Test1 { public static void main(String[] args) { int i=0;
try{ int j=100/i; }catch(ArithmeticException e){ System.out.print("大哥,你出错了!!"); System.out.print(e.printStackTrace()); } System.out.print("该行已被加载!"); } } |
public class Test2{ public static void main(String[] args){ int i=0; try{ int j=100/i; Cat cat=null; }//catch(Exception e){ //System.out.print(e.printStackTrace()); //} catch(ArithmeticException e){ System.out.print("除数不能为0!"); System.out.print(e.getMessage()); //System.out.print(e.printStackTrace()); }catch(NullPointerException e){ System.out.print("抛出了空指针异常!"); } } } class Cat{ void m(){
} } |
public class Test3 { public static void main(String[] args) { Cat cat=null; try{ cat.m(); }catch(NullPointerException e){ System.out.print(e.getMessage()); } } } //下面是一个猫的类,用于说明throw的使用! class Cat { void m()throws NullPointerException{ throw new NullPointerException("出错了!"); } } |