西宁微网站建设,网站建设7个主要流程,网站建设诚信服务,ppt资源网免费异常#xff08;Exception#xff09; JVM 默认处理方案 把异常的名称#xff0c;异常的原因#xff0c;及异常出错的位置等信息输出在控制台程序停止执行 异常类型 编译时异常必须显示处理#xff0c;否则程序会发生错误#xff0c;无法通过编译运行时异常无需显示处理…异常Exception JVM 默认处理方案 把异常的名称异常的原因及异常出错的位置等信息输出在控制台程序停止执行 异常类型 编译时异常必须显示处理否则程序会发生错误无法通过编译运行时异常无需显示处理也可以和编译时异常一样处理 代码示例 异常处理三种方式
try…catch 格式 try{ 可能出现异常的代码
}catch(异常类名 变量名){异常的处理代码e.printStackTrace(); // 打印异常信息
}finally{有无异常都执行的代码
}示例代码 public class Test5 {public static void main(String[] args) {try{//分母不能为 0 很明显错误程序运行到这抛出算术运算异常ArithmeticExceptionint a 5/0;// ①System.out.println(砥砺前行);}catch (Exception e){e.printStackTrace();}finally {System.out.println(欢迎来到编程世界);}}
}①位置因上一行代码异常被抓取到了catch 中进行处理处理完后执行 finally 中代码finally 最经常使用于IO 处理释放流 throws 格式 throws 异常类名 跟在方法的括号后面仅仅是将异常抛出谁调用谁处理main 抛出由 JVM 虚拟机处理 示例代码 public class Test6 {public static void main(String[] args) {try{show();}catch (Exception e){e.printStackTrace();}System.out.println(欢迎来到编程世界);}public static void show() throws ArithmeticException{int a 5/0;System.out.println(a);}
}throw 自定义异常用在方法体内跟的是异常对象名表示抛出异常 格式 throw new Exception(自定义异常);示例代码 public class Test7 {public static void main(String[] args) throws Exception {// 创建键盘输入对象Scanner sc new Scanner(System.in);int i 1;// 三次机会System.out.println(请输入颜色:);while(i 3){String color sc.next();show(color);}}public static void show(String color) throws Exception {if(color.equals(黑色)){throw new Exception(颜色有误);}else if(color.equals(白色)){System.out.println(颜色正确);System.exit(0);}else{System.out.println(请重新输入颜色);}}
}