java虚拟机的默认处理方案会在程序出现异常时结束程序,而实际项目中某一部分出现异常不应该影响后面程序的执行,所以要自己处理异常。
异常祖先类Throwable的成员方法
public class ThrowableTest { public static void main(String[] args) { System.out.println("开始"); method(); System.out.println("结束"); } private static void method() { try { int a[]={1,2}; System.out.println(a[3]); }catch (ArrayIndexOutOfBoundsException e){ // System.out.println(e.getMessage());//3 // System.out.println(e.toString());//java.lang.ArrayIndexOutOfBoundsException: 3 e.printStackTrace(); /* java.lang.ArrayIndexOutOfBoundsException: 3 at _3Exception.ThrowableTest.method(ThrowableTest.java:25) at _3Exception.ThrowableTest.main(ThrowableTest.java:18) */ } } }如果程序出现问题,我们需要自己来处理,有两种方案:
try…catchthrows格式:
try{ 可能出现异常的代码; }catch(异常类名 变量名){ 异常处理代码; }finally{ 必须执行的代码; } public class ExceptionTest1 { public static void main(String[] args) { try { int a[]={1,2}; System.out.println(a[2]); }catch (ArrayIndexOutOfBoundsException e){ System.out.println("越界"); e.printStackTrace(); } System.out.println("结束"); } }虽然我们通过try…catch…可以对异常处理,但不是所有情况我们都有权限进行异常处理,也就是说,有些时候可能出现的异常我们处理不了,这个时候怎么办呢? 针对这个情况,java提供throws解决方案
public class ThrowsTest { public static void main(String[] args) { System.out.println("开始"); method1();//运行时异常如果需要程序继续执行还需要try catch try { method2(); } catch (ParseException e) { e.printStackTrace(); } System.out.println("结束"); } //运行时异常 public static void method1() throws ArrayIndexOutOfBoundsException{ int a[] = {1, 2}; System.out.println(a[2]); } //编译时异常 public static void method2() throws ParseException { String s="2048-08-01"; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date d=sdf.parse(s);//此处有编译异常 System.out.println(d); } } 注意 抛出异常本身没有实质性的处理,真正的处理还是要进行try,catch处理Java提供了throws处理方案。有可能发生异常的语句出现再哪个函数里,就要在该函数的函数首部通过throws声明该异常,在出现问题的情况下通过throw抛出异常。 格式:
返回值类型 方法名称 throws 异常类名{ if(发生异常) throw 异常类对象; }