public static void main(String[] args) { // 可能会出异常的代码,需要使用try来处理,try不能单独使用,必须配合finally或catch使用 try { int i = 10 / 0; System.out.println(i); } catch(Exception e) { // 捕获异常 // 获取异常信息 String message = e.getMessage(); System.out.println("异常信息:" + message); // 一定要打印e.printStackTrace() e.printStackTrace(); } finally { //最终都会执行的(当有必须程序需要处理时) System.out.println(111); } System.out.println(222); } # 运行结果 异常信息:/ by zero 111 222
static void f1() throws Exception { try { int i = 10/0; System.out.println(i); } catch (Exception e) { // 捕获到异常后抛出异常,丢到方法名的后面 throw new Exception(); } } // f1()方法抛出了1个异常,main方法中调用时就需要main方法处理异常 public static void main(String[] args) throws Exception { // 将异常抛给他的父级处理 f1(); }
static Integer f(String str) { try { return Integer.parseInt(str); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("捕获到异常"); } catch(NumberFormatException e) { e.printStackTrace(); } catch (ClassCastException e) { System.out.println("类型转换"); } catch (Exception e) { System.out.println("最大的异常"); } return 0; } // 测试 public static void main(String[] args){ try { int f; f = f("111a"); System.out.println(f); } catch (Exception e) { e.printStackTrace(); } }
// 自定义的异常类需继承Throwable、Exception、RuntimeException public class MyException extends RuntimeException { // 实现序列化id private static final long serialVersionUID = 1L; MyException() { super(); } MyException(String msg) { super(msg); } } public class Test { static void f(String str) throws MyException{ try { int i = Integer.parseInt(str); } catch (MyException e) { System.out.println("111"); throw new MyException("类型转换错误"); } } public static void main(String[] args) { f("a"); } }
throw和throws的区别:
throw在方法体内,表示抛出异常的动作
throws表示可能会抛出的异常类型
异常处理的方式:try-catch或throws
try放可能出现异常的代码,catch捕获后处理;throws在方法头部抛出异常,交给方法的调用者处理
// 给集合指定泛型,那么该集合中只能存入该类型的数据 public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("adc"); }
// 格式:访问修饰符 [static] <T> void 方法名(T t){ 方法体} //可传多个参数 public class Test { // 泛型方法 public static < E > void printArray( E[] inputArray ) { // 输出数组元素 for ( E element : inputArray ){ System.out.printf( "%s ", element ); } System.out.println(); } }