java中的异常包括Error和Exception,其中Error是系统级别的错误比如OutOfMemory会被系统直接杀死,而Exceotion是可捕获可处理的异常,处理之后可以使程序正常运行
/** * Author:DoctorWei * Time:2018/10/29 17:32 * Description:java中有各种不同的异常 java中有些基本的异常时需要处理的 如果不处理最终会叫给jvm处理 导致程序崩溃 * email:1348172474@qq.com */ public class DiffrentException { public void test(){ try { System.out.println(6/0);//.ArithmeticException: / by zero 分母不能为0 } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
public class DiffrentException { public void test(){ try { String[] array=new String[3]; //ArrayIndexOutOfBoundsException String a=array[3];//数组下表越界 长度为3 下标最大为2 从0开始 } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
public class DiffrentException { public void test(){ try { String a=null; //NullPointerException 空指针异常 遇到最多的异常 处理方法 在使用之前先进行null判断 int length = a.length(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
public class DiffrentException { //可以自己定义抛出的异常 在代码块中 public void test() { String a = null; if (a == null) { //Exception in thread "main" java.lang.NullPointerException: 别用空的对象啊 throw new NullPointerException("别用空的对象啊"); } else { int length = a.length(); } } }
public class DiffrentException { //可以自己定义抛出的异常 在代码块中 public void test() { caculate(); } /** * 也可以定义方法 给方法添加一个可能抛出的异常 比如进行运算时出现的数字转换异常 */ public void caculate() throws NullPointerException{ String a="123s"; int num=Integer.parseInt(a); } }
public class DiffrentException { //真正负责的处理方式为try-catch捕获异常之后再处理 public void test() { try { System.out.println(6/0); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { System.out.println("肯定会执行的代码"); } } }