java理论学时第七节。课后作业。
对AboutException.java的理解。在try中如果发出某类系统识别的错误,会以throw的形式抛出,在catch中可以将其截获,不显示在前端,可以选择执行别的代码。
ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException
ArrayIndexOutOfBoundsException/外层try-catch
public class EmbededFinally
{
public static void main(String args[])
{
int result;
try
{
System.out.println("in Level 1");
try
{
System.out.println("in Level 2"); // result=100/0; //Level 2
try
{
System.out.println("in Level 3");
result=100/0; //Level 3
}
catch (Exception e)
{
System.out.println("Level 3:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 3 finally");// result=100/0; //Level 2
}
}
catch (Exception e)
{
System.out.println("Level 2:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 2 finally");// result = 100 / 0; //level 1
}
}
catch (Exception e)
{
System.out.println("Level 1:" + e.getClass().toString());
}
finally
{
System.out.println("In Level 1 finally");
}
}
}
运行结果。
in Level 1
in Level 2
in Level 3
Level 3:class java.lang.ArithmeticException
In Level 3 finally
In Level 2 finally
In Level 1 finally
总结。
这些输出验证了try,catch,finally的运行顺序。与if,else差不多。是先里层再外层的那种。
public class SystemExitAndFinally
{
public static void main(String[] args)
{
try
{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
//System.exit(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
finally
{
System.out.println("in finally");
}
}
}
此时运行程序,in finally不会被打印,可见catch中的退出语句生效了。但在try中退出就会报错,可见这么写是不符合规矩的。
动手动脑。
import javax.swing.JOptionPane;
public class GradeRange
{
public static void main(String[] args)
{
try
{
String str;
double grade;
str = JOptionPane.showInputDialog("请输入某学生的成绩");
//grade = Integer.parseInt(str);
grade = Double.valueOf(str).doubleValue();
if(grade >= 0 && grade < 60)
{
JOptionPane.showMessageDialog(null,"该学生不及格。");
}
else if(grade >= 60 && grade < 70)
{
JOptionPane.showMessageDialog(null,"该学生刚刚及格。");
}
else if(grade >= 70 && grade < 80)
{
JOptionPane.showMessageDialog(null,"该学生成绩中等。");
}
else if(grade >= 80 && grade < 90)
{
JOptionPane.showMessageDialog(null,"该学生成绩良好。");
}
else if(grade >= 90 && grade <= 100)
{
JOptionPane.showMessageDialog(null,"该学生成绩优秀。");
}
else
{
JOptionPane.showMessageDialog(null,"输入数字不在成绩范围内。");
}
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"请输入数字。");
}
}
}
最新文章
- phpweb /version.php Vul
- 如何调试IIS错误信息
- Linux makefile教程之概述一[转]
- fpm打包redis3.0.7
- C#中标准Dispose模式的实现
- BZOJ3315: [Usaco2013 Nov]Pogo-Cow
- 关于android:screenOrientation=";portrait"; 横竖屏切换
- java中的特殊字符集合
- .net 职责链来实现 插件模式
- jar2exe 配置jre
- C++版 - 剑指Offer 面试题39:二叉树的深度(高度)(二叉树深度优先遍历dfs的应用) 题解
- 执行C#动态代码
- WEB学习小笔记
- LeetCode算法题-Two Sum II - Input array is sorted
- C语言的结构和联合,以及PHP是怎么实现弱类型的
- GYM 101755 K.Video Reviews 【贪心】+【二分】
- [转]MySQL中timestamp数据类型的特点
- django--form相关
- linux上搭建nginx
- [OpenCV-Python] OpenCV 中的图像处理 部分 IV (五)