标签:
------- android培训、java培训、期待与您交流! ----------并从这个地方终止程序运行。
public class ExceptionDemo { public static void main(String[] args) { int a = 10; int b = 2; b = 0; // ArithmeticException System.out.println(a / b); System.out.println("over"); } }(4)我们自己如何针对程序进行处理:
try...catch... try...catch...catch... try...catch...finally... try...catch...catch...finally... try...finally...
try{ }catch(){ }catch(){ }
JDK7的新特性:这个要求都是平级关系。
public class ExceptionDemo3 { public static void main(String[] args) { int a = 10; int b = 0; int[] arr = { 1, 2, 3 }; try { System.out.println(a / b); System.out.println(arr[3]); // ...代码一大堆,还可能有问题,但是我不太明确是什么问题。肿么办 // 用Exception解决 } catch (ArithmeticException e) { System.out.println("除数不能为0"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组索引越界"); } catch (Exception e) { System.out.println("程序出现了问题"); } // JDK7改进的代码 try { System.out.println(a / b); System.out.println(arr[3]); } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println("程序出现了小问题"); } System.out.println("over"); } }
如果后面根据的是Exception及其子类,那么,必须要编写代码进行处理,或者调用的时候抛出。
public class Teacher2 { public void checkScore(int score) throws ScoreException { if (score < 0 || score > 100) { throw new ScoreException("分数必须是0-100之间"); } else { System.out.println("分数正常"); } } }B:throw
如果方法中,有throw抛出Exception及其子类,那么,声明上必须有throws。
public class Teacher { public void checkScore(int score) { if (score < 0 || score > 100) { throw new ScoreException("分数必须是0-100之间"); } else { System.out.println("分数正常"); } }(7)自定义异常
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/chaoyangmemory/article/details/46698191