首页 / JAVA / java异常处理动手动脑问题
java异常处理动手动脑问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java异常处理动手动脑问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2216字,纯文字阅读大概需要4分钟。
内容图文
![java异常处理动手动脑问题](/upload/InfoBanner/zyjiaocheng/1179/d92719d9fbdb4cb0a8874ea93f057ce5.jpg)
动手动脑01
源程序:
import javax.swing.*;
class AboutException {
public static void main(String[] a)
{
int i=1, j=0, k;
k=i/j;
try
{
k = i/j; // Causes division-by-zero exception
//throw new Exception("Hello.Exception!");
}
catch ( ArithmeticException e)
{
System.out.println("被0除. "+ e.getMessage());
}
catch (Exception e)
{
if (e instanceof ArithmeticException)
System.out.println("被0除");
else
{
System.out.println(e.getMessage());
}
}
finally
{
JOptionPane.showConfirmDialog(null,"OK");
}
}
}
程序截图:
动手动脑:多层的异常捕获-1
源程序:
public class CatchWho {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("发生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");
}
}
}
程序截图:
动手动脑:多层的异常捕获-2
源程序:
public class CatchWho2 {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArithmeticException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("发生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");
}
}
}
程序截图:
动手动脑-----
当有多个嵌套的try...catch....finally时,要特别注意finally的执行时机
代码示例:
执行结果:
注意:
当有多层嵌套的finally时,异常在不同层次抛出,在不同的位置抛出,可能导致不同的finally语句执行顺序
动手动脑--------
辨析:finally语句一定会1执行吗?
示例代码:
执行结果:
总结:
(1)try语句没有被执行到,如在try语句之前return就返回了,这样finally语句就不会执行。这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。
(2)在try块|catch块中有System.exit(0);这样的语句。System.exit(0)是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。
在try-catch-finally中, 当return遇到finally,return对finally无效,即:
1.在try catch块里return的时候,finally也会被执行。
2.finally里的return语句会把try catch块里的return语句效果给覆盖掉。
结论:return语句并不一定都是函数的出口,执行return时,只是把return后面的值复制了一份到返回值变量里去了。(总结部分来源于网络)
验证:
由图可知不能通过编译
但是修正代码后得以编译
为什么?
throws语句表明某种方法可能出现某种异常,而它自己不能处理,而需要由调用者来处理
原文:http://www.cnblogs.com/lovema1210/p/7846186.html
内容总结
以上是互联网集市为您收集整理的java异常处理动手动脑问题全部内容,希望文章能够帮你解决java异常处理动手动脑问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。