ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 异常处理 ~~~java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ExceptionClass { public static void main(String[] args) throws Exception {//main方法也被称之为主线程 String str = "2018/07/11 12:21:51"; System.out.println("**********程序开始运行**********"); age(17); System.out.println("**********程序结束运行**********"); } public static void age(int age) throws Exception { if(age < 18) { throw new Exception("您的年龄不合法"); } else { System.out.println("您已进入vip房间"); } } public static void fun3(String str, String subStr) { try { if(str.indexOf(subStr) >= 0) { System.out.println("存在子串"); } else { System.out.println("不存在子串"); } //int a = 10 / 0;//如果捕获的异常种类和发生异常种类不能对应上,那么程序也会终止运行 } /*catch(NullPointerException e) { //e.printStackTrace();//该方法可以在控制台打印异常种类,错误信息和出错位置 System.out.println(e.toString());//获得异常的种类和错误信息 System.out.println(e.getMessage());//获得错误信息 } catch(ArithmeticException e) { e.printStackTrace(); }*/ /*catch(Exception e) { System.out.println("aaa");//catch区域的内容,如果不出现异常,则不会执行 e.printStackTrace(); }*/ finally { System.out.println("111"); } } /** * 使用throws处理异常,程序发生异常,不存在try-catch的作用,会终止程序的运行 * @param str * @throws ParseException */ public static void parseDate(String str) throws ParseException{//抛出异常,代表着我这个方法不处理我这边抛出的异常,留给调用我方法的地方处理 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(str); date.getTime(); System.out.println(str); } /** * 找错误手册 * 1.程序出现异常之后,打开控制台,查看打印的异常信息 * 2.找到出现异常的方法,在出现异常的地方附近打断点 * 3.采用debug模式运行,进入调试模式,找到错误的根本原因 * 4.修改错误 */ //断点其实像把程序执行流卡在某个位置,等待人工确认运行 public static void exceptionStudy1() { System.out.println("**************程序1开始运行***************"); System.out.println("**************程序1开始数学运算:"+ 10/2 +"***************"); System.out.println("**************程序1结束运行***************"); } public static void exceptionStudy2() { System.out.println("**************程序2开始运行***************"); System.out.println("**************程序2开始数学运算:"+ 10/0 +"***************"); System.out.println("**************程序2结束运行***************"); } /** * 如果异常不会发生,也就意味着处理了异常 * 判断subStr是否存在str内 */ public static void fun(String str, String subStr) { if(str != null && subStr != null) { if(str.indexOf(subStr) >= 0) { System.out.println("存在子串"); } else { System.out.println("不存在子串"); } } else { System.out.println("不合法字符串"); } } } ~~~