使用try…catch
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub try { System.out.println("try start"); int i = 1 / 0; System.out.println("try end"); } catch (Exception e) { // TODO: handle exception System.out.println("catch"); e.printStackTrace(); } finally { System.out.println("finally"); } } }
運行結果
try start catch finally java.lang.ArithmeticException: / by zero at Test.main(Test.java:12)
運行時例外
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub if (true) { RuntimeException e = new RuntimeException("產生例外"); throw e; } } }
運行結果
Exception in thread "main" java.lang.RuntimeException: 產生例外
at Test.main(Test.java:12)使用throws
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub if (true) { Exception e = new Exception("產生例外"); throw e; } } }
運行結果
Exception in thread "main" java.lang.Exception: 產生例外
at Test.main(Test.java:12)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/17420.html
標籤:Java
