1.异常处理

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");
}
}
}

使用Java异常处理机制

把可能会发生错误的代码放进try语句块中。当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误。catch语句块中的代码用于处理错误。当异常发生时,程序控制流程由try语句块跳转到catch语句块。不管是否有异常发生,finally语句块中的语句始终保证被执行。如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

Throwable类有两个直接子类:

Exception:出现的问题是可以被捕获的;

Error:系统错误,通常由JVM处理。

可捕获的异常又可以分为两类:

(1)Check异常:直接派生自Exception的异常类,必须被捕获或再次声明抛出

(2)Runtime异常:派生自RuntimeException的异常类。

2.以下代码在运行时不会引发异常,解释原因。

public class ThrowDemo {
public static void main(String[] args) {
// try {
double data = 100 / 0.0;
System.out.println("浮点数除以零:" + data);
// if(String.valueOf(data).equals("Infinity"))
// {
// System.out.println("In Here" );
// throw new ArithmeticException("除零异常");
// }
// }
// catch(ArithmeticException e) {
// System.out.println(e);
// }
}
}

JVM在具体实现这两个指令时,采用了不同的处理策略,导致两段代码运行时得到不同的结果

3.异常的“多态”特性

可以有多个catch语句块,每个代码块捕获一种异常。在某个try块后有两个不同的catch 块捕获两个相同类型的异常是语法错误。

使用catch语句,只能捕获Exception类及其子类的对象。因此,一个捕获Exception对象的catch语句块可以捕获所有“可捕获”的异常。

将catch(Exception e)放在别的catch块前面会使这些catch块都不执行,因此Java不会编译这个程序。

4.finally”的功用

资源泄露:当一个资源不再被某应用程序使用,但此程序并未向系统声明不再使用此资源时发生这种情况

finally语句块主要用于解决资源泄露问题,它位于catch语句块之后,JVM保证它们一定执行。

注意:finally语句块中也可能发生异常,如果这种情况发生,先前的异常被放弃。

5.阅读以下代码,写出程序运行结果

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");
}
}
}

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");
}
}
}

6. 阅读以下代码,写出程序运行结果

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");
}
}
}

总结:

当有多层嵌套的finally时,异常在不同的层次抛出,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

7. finally语句块一定会执行吗?

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");
}
}
}

不一定,因为System.exit(0);finally不执行。

8.异常的传播路径

// UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class PrintExceptionStack {
public static void main( String args[] ){
try {
method1();
}
catch ( Exception e ) {
System.err.println( e.getMessage() + "\n" );
e.printStackTrace();
}
}
public static void method1() throws Exception{
method2();
}
public static void method2() throws Exception{
method3();
}
public static void method3() throws Exception{
throw new Exception( "Exception thrown in method3" );
}
}

总结:

Try语句可以被嵌套。也就是说,一个try语句可以在另一个try块内部。每次进入try语句,异常的前后关系都会被推入堆栈。如果一个内部的try语句不含特殊异常的catch处理程序,堆栈将弹出,下一个try语句的catch处理程序将检查是否与之匹配。这个过程将继续直到一个catch语句匹配成功,或者是直到所有的嵌套try语句被检查耗尽。如果没有catch语句匹配,Java的运行时系统将处理这个异常。

9.受控异常与不受控异常

throws语句中声明的异常称为受控(checked)的异常,通常直接派生自Exception类。

RuntimeException(其基类为Exception) 和Error(基类为Throwable)称为非受控的异常。这种异常不用在throws语句中声明。

例子:

import java.io.*;
public class CheckedExceptionDemo {
public static void main(String[] args) {
try {
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in)); //抛出受控的异常
System.out.print("请输入整数: ");
int input = Integer.parseInt(buf.readLine()); //有可能引发运行时异常
System.out.println("input x 10 = " + (input*10));
}
//以下异常处理语句块是必须的,否则无法通过编译
catch(IOException e) {
System.out.println("I/O错误");
}
//以下异常处理语句块可以省略,不影响编译,但在运行时出错
catch(NumberFormatException e) {
System.out.println("输入必须为整数");
}
}
}

10.编写一个程序,此程序在运行时要求用户输入一个整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。
要求程序必须具备足够的健壮性,不管用户输入什么样的内容,都不会崩溃。
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
int score = 0;
System.out.print("输入一个整数:");
Scanner sc = new Scanner(System.in);
try{
score = sc.nextInt();
if(score < 0 || score >100){
throw new InputMismatchException();
}
}
catch(InputMismatchException e){
System.out.println("输入必须为整数(0-100之间)");
System.exit(0);
}
if(score >= 0 && score <=100){
if(score >= 90){
System.out.println("优");
}
else if(score >= 80){
System.out.println("良");
}
else if(score >= 70){
System.out.println("中");
}
else if(score >= 60){
System.out.println("及格");
}
else{
System.out.println("不及格");
}
}
}
}

java课后实验性问题7的更多相关文章

  1. java课后实验性问题5

    课后作业一:字符串加密 程序设计思想: 从键盘获取字符串,将字符串转为字符数组,将每个元素加事前协定的“key”,再转为字符串输出. 程序流程图: 源代码: import java.util.Scan ...

  2. java课后实验性问题4

    课后作业一: 使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数.请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象? 设计思路:定义类的构造函数时使静态变量i进行i++,即每构 ...

  3. java课后实验性问题2

    课后作业一:计算组合数 程序设计思想: 从键盘获取组合数,判断是否构成组合数.分别用三种方法计算组合数输出. 程序流程图: import java.util.Scanner; public class ...

  4. java课后实验性问题6

    1.继承条件下的构造方法调用. class Grandparent { public Grandparent(){ System.out.println("GrandParent Creat ...

  5. java课后实验性问题3

    一 .生成随机数 import java.util.*; public class Test1 { public static void main(String[] args) { //建立一个生产随 ...

  6. java课后实验性问题1

    一.一个java类文件中只能有一个公有类吗? 测试代码 public class Test{ public static void main(String[] args){ } public clas ...

  7. JAVA 数组作业——动手动脑以及课后实验性问题

    JAVA课后作业——动手动脑 一:阅读并运行示例PassArray.java,观察并分析程序输出的结果,小结,然后与下页幻灯片所讲的内容进行对照. 1.源代码 // PassArray.java // ...

  8. JAVA语法基础作业——动手动脑以及课后实验性问题 (八)

    一.动手动脑 运行AboutException.java示例,了解Java中实现异常处理的基础知识. 1)源代码 import javax.swing.*; class AboutException ...

  9. JAVA 多态和异常处理作业——动手动脑以及课后实验性问题

    1.  阅读以下代码(CatchWho.java),写出程序运行结果: 1)  源代码 public class CatchWho { public static void main(String[] ...

随机推荐

  1. springboot启动流程(三)Environment简介

    所有文章 https://www.cnblogs.com/lay2017/p/11478237.html 简介 上一篇文章中,我们简单了解了一下SpringApplication的run方法的代码逻辑 ...

  2. 运动的border,仿当当简易效果

    突然想到以前看到当当上有个效果,当鼠标移上去,图片边框是运动添加上的,还以为是css3或者是canvas做的呢,做完幽灵按钮后,才知道,so  easy,只不过是animate+position的杰作 ...

  3. S2-033、S2-037

    前言 S2-033漏洞和S2-032类似,也是由于开启了动态方法调用,action mapper中的执行的方法名可控,导致了ognl表达式注入. 正文 Rest插件中获取action mapper是用 ...

  4. svm 简单明了的入门级使用教程(转载)

    如何使用libsvm进行分类   这帖子就是初步教教刚接触libsvm(svm)的同学如何利用libsvm进行分类预测,关于参数寻优的问题在这里姑且不谈,另有帖子详述. 其实使用libsvm进行分类很 ...

  5. C#面向对象 什么是面向对象

    1.面向对象(Object Oriented,OO) 是当前计算机界关心的重点,它是90年代软件开发方法的主流.面向对象的概念和应用已超越了程序设计和软件开发,扩展到很宽的范围.如数据库系统.交互式界 ...

  6. Image Processing and Analysis_15_Image Registration:A survey of medical image registration——1998

    此主要讨论图像处理与分析.虽然计算机视觉部分的有些内容比如特 征提取等也可以归结到图像分析中来,但鉴于它们与计算机视觉的紧密联系,以 及它们的出处,没有把它们纳入到图像处理与分析中来.同样,这里面也有 ...

  7. 【问题】XShell连接不上Debian root用户

    类似文章:https://www.lianst.com/3231.html 修改此文件 重启ssh服务 ssh restart有问题,换一条命令OK 你的Linux发行版可能不一样,针对CentOS参 ...

  8. socket 编程的一些应用例子

    1.#传输文件的例子 import socketfrom socket import *import osimport requests import time,socketserver,struct ...

  9. Linux系统运维之修炼秘法

    在这个现如今的互联网高速发展的时代,如何才能保持住一门铁的饭碗.无疑最稳妥的自然就是选择一门任何时代都不会落伍的技能,来选择深入学习研究.大家可能觉得这一期的Linux就该这么学的话题比较世俗.但是不 ...

  10. TODO:AppiumTestDistribution--CapabilityManager 类

    该类代码详见git:https://github.com/AppiumTestDistribution/AppiumTestDistribution/tree/master/src/main/java ...