Java 实例 - 获取异常的堆栈信息
以下实例演示了使用异常类的 printStack() 方法来获取堆栈信息:
public class Main{ public static void main (String args[]){ int array[]={20,20,40}; int num1=15,num2=10; int result=10; try{ result = num1/num2; System.out.println("The result is" +result); for(int i =5; i>=0; i--) { System.out.println("The value of array is" +array[i]); } } catch (Exception e) { e.printStackTrace(); } } }
以上代码运行输出结果为:
The result is1 java.lang.ArrayIndexOutOfBoundsException: 5 at testapp.Main.main(Main.java:28)
Java 实例 - 重载方法异常处理
以下实例演示了重载方法的异常处理
public class Main { double method(int i) throws Exception{ return i/0; } boolean method(boolean b) { return !b; } static double method(int x, double y) throws Exception { return x + y ; } static double method(double x, double y) { return x + y - 3; } public static void main(String[] args) { Main mn = new Main(); try{ System.out.println(method(10, 20.0)); System.out.println(method(10.0, 20)); System.out.println(method(10.0, 20.0)); System.out.println(mn.method(10)); } catch (Exception ex){ System.out.println("exception occoure: "+ ex); } } }
以上代码运行输出结果为:
30.0 27.0 27.0 exception occoure: java.lang.ArithmeticException: / by zero
Java 实例 - 链试异常
以下实例演示了使用多个 catch 来处理链试异常:
public class Main { public static void main (String args[])throws Exception { int n=20,result=0; try{ result=n/0; System.out.println("结果为"+result); } catch(ArithmeticException ex){ System.out.println("发算术异常: "+ex); try { throw new NumberFormatException(); } catch(NumberFormatException ex1) { System.out.println("手动抛出链试异常 : "+ex1); } } } }
以上代码运行输出结果为:
发算术异常: java.lang.ArithmeticException: / by zero 手动抛出链试异常 : java.lang.NumberFormatException
Java 实例 - 自定义异常
以下实例演示了通过继承 Exception 来实现自定义异常:
class WrongInputException extends Exception { // 自定义的类 WrongInputException(String s) { super(s); } } class Input { void method() throws WrongInputException { throw new WrongInputException("Wrong input"); // 抛出自定义的类 } } class TestInput { public static void main(String[] args){ try { new Input().method(); } catch(WrongInputException wie) { System.out.println(wie.getMessage()); } } }
以上代码运行输出结果为:
Wrong input