------Java EE培训、Android培训、iOS培训、期待与您交流! -------
来看一段代码:
class ExceptionDemo{ public static void main(String[] args) { byte[] buf = new byte[1024*1024*700];//java.lang.OutOfMemoryError } }
程序在运行时出现的不正常情况,比如角标越界,空指针,违反数学法则等。这个问题按照面向对象思想进行描述,并封装成了对象。因为问题的产生有产生的原因、名称、描述等多种属性信息存在。当出现多属性信息时最方便的方式就是将这些信息进行封装。异常就是java按照面向对象的思想将问题进行对象封装。
异常被抛出后,调用者必须处理,否则会编译失败。代码中抛出了几个异常,调用者就必须处理几个。
异常的处理方式
1,使用try catch finally 捕获。把可能出现异常的代码入 try{ 代码 } 中。
注意:finally代码块:一定会执行,一般用于关闭资源。
有一个特殊情况下finally不会执行,它前面有 System.exit(0); 退出语句时 不会执行。
2,直接再抛出异常。这种方式就是让其调用者自己去处理。
注意:如果程序中出现了异常,要么在内部try catch 处理,要么在函数上声明让调用者处理。
class divide { int div(int a,int b) throws Exception { //if(b<0) //{ // throw new minusZeroException(); //} int[] arr = new int[a]; System.out.println(arr[a]); return a/b; } } public class singleMode { public static void main(String[] args) { //Manager m = new Manager("tom","m01",123); divide d = new divide(); try { int x = d.div(4,0); } catch(ArithmeticException e) { System.out.println(e.toString()); } catch (Exception e) { //System.out.println("you can't divide zero!"); System.out.println(e.toString()); e.printStackTrace(); } System.out.println("end"); } }
这样写真的好吗?
interface Shape { //void calculate(); void getArea(); } class Rec implements Shape { private int len,wid; Rec(int len,int wid) { if(len <=0 || wid<=0) System.out.println("不正确的赋值"); else { this.len = len; this.wid = wid; } } public void getArea() { System.out.println(len*wid); } } public class singleMode { public static void main(String[] args) { Rec rectan = new Rec(3,4); rectan.getArea(); } }
class wrongValueException extends Exception { wrongValueException(String msg) { super(msg); } } interface Shape { //void calculate(); void getArea(); } class Rec implements Shape { private int len,wid; Rec(int len,int wid) throws wrongValueException { if(len <=0 || wid<=0) throw new wrongValueException("赋值无效!"); this.len = len; this.wid = wid; } public void getArea() { System.out.println(len*wid); } } public class singleMode { public static void main(String[] args) { try { Rec rectan = new Rec(3,- 4); rectan.getArea(); } catch (wrongValueException e) { System.out.println(e.toString()); } } }
throw与throws区别?
1,throws 抛出异常(用在函数上)
throw 抛出自定义的那种异常(用在函数内)如:throw new RuntimeException("传入类型不符!")
2,throws 后面跟异常类,可以跟多个,用逗号隔开
throw 后跟的是异常对象