java异常
1.异常分类
a.运行时异常:代码在编辑时不报错,运行时才报错
b.检查异常:代码在编辑时报错
2.处理异常: try catch或者throws
try: 将可能可能发生异常的代码用{}包裹起来
catch:捕获特定类型的异常,捕获时先写范围小的类型,后写范围大的类型
如果try中的代码确实发生了异常,则程序不再执行try中异常之后的代码,而是直接跳到catch中执行
### try catch
自己当前能够处理
###throws
自己当前方法不能处理上交给上级(方法调用处)处理,使用throws
###finally
无论正常还是异常,始终会执行的代码
a.即使遇到return,也仍然会执行
b.除非虚拟机关闭,才不会执行System.exit(1);//关闭虚拟机jvm
1 package ex; 2 3 public class Demo1 { 4 public static void test01() { 5 Object obj = null; 6 try { 7 obj.equals("");// 可能产生异常的代码 8 9 } catch (NullPointerException e) {// 捕获特定类型的异常 10 System.out.println("发生了空指针异常"); 11 } finally { 12 System.out.println("无论正常,还是异常,始终都会执行的代码。。。"); 13 } 14 15 } 16 17 public static int test02() { 18 try { 19 Object obj = null; 20 // System.exit(1);//关闭jvm 21 obj.equals(""); 22 return 1; 23 } catch (NullPointerException e) { 24 return 0; 25 } finally { 26 System.out.println("照样执行>>>"); 27 } 28 } 29 30 // 多个catch只执行一个类似if else if 31 public static void test03() { 32 try { 33 // Class.forName("xxx");//程序会加载指定的类 34 Object obj = null; 35 obj.equals("");// 空指针 36 int[] a = new int[3]; 37 a[4] = 4;// 数组越界异常 38 } catch (ArrayIndexOutOfBoundsException e) { 39 System.out.println("数组越界异常...."); 40 } catch (NullPointerException e) {// 捕获空指针 41 System.out.println("发生了空指针异常"); 42 } catch (Exception e) {// 还有一些想不到的异常 43 System.out.println("其他异常>>>>"); 44 System.out.println(e); 45 e.printStackTrace();// 打印异常的堆栈信息 46 System.out.println("getMessage" + e.getMessage()); 47 } 48 49 } 50 51 public static void test04() throws NullPointerException, ClassNotFoundException {// 抛出异常给上级 52 Object obj = null; 53 obj.equals("");// 空指针 54 Class.forName("xxx"); 55 56 } 57 58 public static void main(String[] args) throws Exception {// 上级接收到异常后要么自己trycatch处理要么继续往上抛出 59 // test01(); 60 // test02(); 61 // test03(); 62 test04(); 63 } 64 }
###throw一般和自定义异常一起使用
throw:声明异常
jdk中自带了很多类型的异常,但这些内置异常如果还不够用的话,那就需要自定义异常
编写自定义异常
类,继承Exception,调用super("异常信息")
1 package ex; 2 3 public class MyException extends Exception { 4 public MyException(String message) {//异常信息 5 super(message); 6 } 7 } 8 9 10 11 package ex; 12 13 public class Demo2 { 14 15 public static void main(String[] args) { 16 int age=188; 17 //约定,年龄不能大于120 18 if(age<=0||age>120) { 19 try { 20 //手工声明一个异常 21 throw new MyException("年龄不能大于120"); 22 }catch(MyException e) { 23 e.printStackTrace(); 24 System.out.println(e.getMessage()); 25 } 26 } 27 } 28 29 }
道阻且长,行则将至

浙公网安备 33010602011771号