java:处理程序中的错误
try-catch捕获异常
public static void main(String[] args) { float sum=0; for(String argumentString:args) { try { sum+=Float.parseFloat(argumentString); } catch (Exception e) { System.out.println(argumentString+" is not a number"); // TODO: handle exception } } System.out.println("Those numbers add up to "+sum); }
运行该程序之前,先对命令行参数进行配置,选择Run->Set ProjectConfiguration->Customize命令,手动输入 1 3 5x。运行后输出:
5x is not a number
Those numbers add up to 4.0
拓展
//捕获多种不同的异常 try { }catch (NumberFormatException e) { // TODO: handle exception }catch(ArithmeticException e) { } //或者 try { }catch (NumberFormatException |ArithmeticException e) { // TODO: handle exception }
//出现异常后处理 try { }catch (Exception e) { // TODO: handle exception }finally { //finally部分的语句将其他语句执行后执行,不管是否发生异常。 }
//throw抛出异常 try { }catch (Exception e) { // TODO: handle exception throw e;//可以先处理异常然后抛出异常 }finally { //finally部分的语句将其他语句执行后执行,不管是否发生异常。 }
//应用于捕获异常的final 关键字 String str="asd"; try { int a=Integer.parseInt(str); }catch (final Exception e) {//final关键字会导致throw语句在执行时,表现出不同的行为,即抛出所捕获的特定异常类 System.out.println("Error "+e.getMessage()); throw e; }
ps:当在捕获父类异常(比如:Exception)的catch块中使用throw时,会抛出该父类的异常。这样无法获悉所发生错误的详情,因为子类异常(比如NumberFormatException)提供的信息要比Exception类更为详细。
java使用final关键字来记录异常的详情。在上面代码中final Exception e == NumberFormatException e
ps_ps:JLS 14.20:In a uni-catch clause, an exception parameter that is not declared final (implicitly or explicitly) is considered effectively final if it never occurs within its scope as the left-hand operand of an assignment operator.
翻译:在 uni-catch 子句中,如果异常参数从未作为赋值运算符的左侧操作数出现在其范围内,则未声明为 final(隐式或显式)的异常参数被认为是有效的 final。
故在上面代码中,除非在catch中修改异常,在代码中final Exception e和Exception e在结果上是没有差异的。
2021.09.14

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号