JAVA异常处理机制
JAVA中异常处理机制:
JAVA语言提供两种异常处理机制:捕获异常和声明抛弃异常
1)捕获异常:在Java程序运行过程中系统得到一个异常对象是,它将会沿着方法的调用栈逐层回溯,寻找处理这一异常的代码。找到能够处理这种类型异常的方法后,运行时系统把当前异常交给这个方法处理;如果找不到可以捕获异常的方法,则运行时系统将终止,相应的Java程序也将退出。
2)声明抛弃异常:当Java程序运行时系统得到一个异常对象时,如果一个方法并不知道如何处理所出现的异常,则可在方法声明时,声明抛弃异常。声明抛弃异常是在一个方法声明中的throws子句中指明的。
下面将通过若干个例子说明JAVA中异常处理机制
一:AboutException.java
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import javax.swing.*; class AboutException { public static void main(String[] a) { double i= 1 , j= 0 , k; k=i/j; try { k = i/j; // Causes division-by-zero exception //throw new Exception("Hello.Exception!"); } catch ( ArithmeticException e) { System.out.println( "被0除. " + e.getMessage()); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println( "被0除" ); else { System.out.println(e.getMessage()); } } finally { JOptionPane.showConfirmDialog( null , "OK" ); System.out.println(+k); } } } |
结果截图:
分析:
程序中,当i,j的数据类型改为整型的话,程序会抛出Exception的错误,导致程序无法正常运行,如果把i,j改为double类型是,程序输出无穷大这一结果;
JAVA异常处理机制:
把可能会发生错误的代码放进try语句块中。
当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误。
catch语句块中的代码用于处理错误。
当异常发生时,程序控制流程由try语句块跳转到catch语句块。
不管是否有异常发生,finally语句块中的语句始终保证被执行。
如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。
二:CatchWho.java
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class CatchWho { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch" ); } throw new ArithmeticException(); } catch (ArithmeticException e) { System.out.println( "发生ArithmeticException" ); } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch" ); } } } |
运行结果:
三:CatchWho2.java
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class CatchWho2 { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch (ArithmeticException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch" ); } throw new ArithmeticException(); } catch (ArithmeticException e) { System.out.println( "发生ArithmeticException" ); } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch" ); } } } |
运行结果:
四:EmbedFinally.java
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | public class EmbededFinally { public static void main(String args[]) { int result; try { System.out.println( "in Level 1" ); try { System.out.println( "in Level 2" ); // result=100/0; //Level 2 try { System.out.println( "in Level 3" ); result= 100 / 0 ; //Level 3 } catch (Exception e) { System.out.println( "Level 3:" + e.getClass().toString()); } finally { System.out.println( "In Level 3 finally" ); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println( "Level 2:" + e.getClass().toString()); } finally { System.out.println( "In Level 2 finally" ); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println( "Level 1:" + e.getClass().toString()); } finally { . System.out.println( "In Level 1 finally" ); } } } |
运行结果:程序无法运行!
分析:源代码中69行出多了一个“.”,若将其删除,会有如下的运行结果:
五:finally语句一定会执行吗?
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class SystemExitAndFinally { public static void main(String[] args) { try { System.out.println( "in main" ); throw new Exception( "Exception is thrown in main" ); //System.exit(0); } catch (Exception e) { System.out.println(e.getMessage()); System.exit( 0 ); } finally { System.out.println( "in finally" ); } } } |
运行截图:
分析:
当有多层嵌套的finally时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序
六:如何跟踪异常的传播路径?
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // UsingExceptions.java // Demonstrating the getMessage and printStackTrace // methods inherited into all exception classes. public class PrintExceptionStack { public static void main( String args[] ) { try { method1(); } catch ( Exception e ) { System.err.println( e.getMessage() + "\n" ); e.printStackTrace(); } } public static void method1() throws Exception { method2(); } public static void method2() throws Exception { method3(); } public static void method3() throws Exception { throw new Exception( "Exception thrown in method3" ); } } |
运行截图:
分析:
当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。
可使用printStackTrace 和 getMessage方法了解异常发生的情况:
printStackTrace:打印方法调用堆栈。
每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。
七:设计型程序(根据输入的=成绩,判断该门功课的水平“包括异常处理机制,及不管用户输入什么内容,都不会崩溃”)
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | package tichangchuli; import java.util.Scanner; @SuppressWarnings ( "serial" ) class ChenjiException extends Exception{ public ChenjiException(String s) { super (s); } } public class chengji { public static boolean Test(String ss){ boolean flag= true ; char []chArr=ss.toCharArray(); int l=ss.length(); for ( int i= 0 ;i<l;i++){ if (chArr[i]< 48 ||chArr[i]> 57 ) {flag= false ;} } return flag; } public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings ( "resource" ) Scanner in= new Scanner(System.in); System.out.println( "请输入学生成绩" ); try { String u=in.next(); if (Test(u)) { int chengj=Integer.parseInt(u); if (chengj>= 90 ) { System.out.println( "优" ); } else if (chengj< 90 &&chengj>= 80 ) { System.out.println( "良" ); } else if (chengj< 80 &&chengj>= 70 ) { System.out.println( "中" ); } else if (chengj< 70 &&chengj>= 60 ) { System.out.println( "及格" ); } else { System.out.println( "不及格" ); } } else throw new ChenjiException( "输入格式不正确!" ); } catch (ChenjiException e) { System.out.println(e); } } } |
结果截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了