java-异常
异常
定义:在程序执行过程中,遇到的不正常的现象
error:错误,人为原因产生的,在程序中必须要解决的内容
exception:异常,在程序中可能出现的情况,需要我们人为的避免
2.编译时异常(在编译的时候就有,不处理不能运行)
NullPointerException:空指针异常
ArrayIndexOutOfBoundsException:数组下标越界异常
ArithmeticException 数学异常
@Test public void test04(){ //ClassCastException 类型转换异常 // Object obj = new String("tom"); // Date date = (Date)obj; // System.out.println(date); //ArrayIndexOutOfBoundsException 数组下标越界异常 // int [] arr=new int[2]; // arr[0]=10; // arr[1]=11; // arr[2]=12; // System.out.println(arr[2]); // NullPointerException 空指针异常 int [] arr=null; System.out.println(arr[1]);
如何使用异常
try catch throw throws finally
try : 将可能出现异常的代码都放入try中
@Test public void test05() { TestException e = new TestException(); try { e.show(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void show() throws Exception{ int [] arr =null; System.out.println(arr[1]); }
抛出异常,我们直接在程序中写异常信息
public void setSex(String sex) { /** * 如果赋值的是男或者女则正常赋值否则给出异常提示 */ if("男".equals(sex) || "女".equals(sex)){ this.sex = sex; }else{ //抛出异常 try { throw new Exception("性别赋值不正确"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

浙公网安备 33010602011771号