java--异常处理总结

it2022-05-30  81

[在程序中抛出异常]

  在程序中抛出异常,一定要使用关键字throw.  throw+异常实例对象。

  

1 public class Demo2 { 2 public static void main(String[] args) { 3 int a = 10; 4 int b = 0; 5 try{ 6 if(b==0) throw new ArithmeticException("除数不能为零!"); 7 else 8 System.out.println("a/b = "+a/b); 9 } 10 catch(ArithmeticException e){ 11 System.out.println("异常为 "+e); 12 } 13 } 14 }

[指定方法抛出异常]

  如果在方法内部的程序代码也会出现异常,且方法内部还没有捕获该异常的代码块,则必须在生命方法的同时一并指出所有肯能发生的异常,以便调用该方法的程序得以做好准备来捕获异常。

  方法 throws 异常1,异常2……

class Test{ // 在指定方法中抛出异常,但是不处理它。 public void add(int a,int b) throws Exception { int c = a/b; System.out.println(a+"/"+b+" = "+c); } } public class Demo2 { public static void main(String[] args) { Test test = new Test(); try { test.add(4,0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

  抛出异常。

  上述的代码中,如果在main()函数中抛出异常 throws Exception,整个程序还是能够变异通过的.这也就说明了异常的抛出是向上抛出的,main() 是整个程序的最低点。

[编写自己的异常类]

  java可通过继承的方式编写自己的异常类。因为所有可处理的异常类均继承自Exception类,所以自定义异常类也必须继承这个类。\\

  自己编写异常类的语法如下:

  class 异常名称 extends Exception  {  … …  }

  

1 class DefaultException extends Exception { 2 public DefaultException(String msg) { 3 super(msg); 4 } 5 } 6 public class Demo3 { 7 public static void main(String[] args) { 8 try{ 9 throw new DefaultException("Hello, 自定义的异常!"); 10 } 11 catch(DefaultException e){ 12 System.out.println(e); 13 } 14 } 15 }

  之所以使用super(msg)是因为父类Exception:Exception构造方法:                            public Exception(String message)

转载于:https://www.cnblogs.com/plxx/p/3365327.html


最新回复(0)