当前位置:文档之家› JAVA实验四异常处理

JAVA实验四异常处理

实验四异常处理
实验目的
1、掌握异常的概念和Java异常处理机制。
2、掌握异常的定义、抛出和捕捉处理。
实验内容与要求
1、仔细读下面的JAVA语言源程序,自己给出程序的运行结果
import java.io.*;
public class Ch31 {
public static void main(String args[])throws IOException {
MyException(int a) {
x=a;
}
public String toString() {
return "自定义异常类MyException";
}
}
public class LX33 {
static void mathod(int a) throws MyException {
//声明方法会抛出MyException
实验内容
五、实验体会
System.err.println("exception msg:" + e.getMessage());
System.err.println("exception string:" + e.toString());
e.printStackTrace();
}finally{
System.out.println("-------------------");
int[] ko=new int[15];
int n,a;
String x;
BufferedReader keyin=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an integer:");
(1)程序功能:通过继承Exception异常类创建一个自定义异常类MyException,然后再创建一个主类LX33使用自定义异常类MyException。
(2)编写LX33.java程序文件,源代码如下。
class MyException extends Exception {
private int x;
x=keyin.readLine();
n=Integer.parseInt(x);
try {
a=110/n;
ko[15]=100;
System.out.println("此描述无法执行!");
} catch(ArithmeticException e){
System.out.println("除数为0的错误");
System.out.println("\t此处引用mathod ("+a+")");
if (a>10) throw new MyException(a); //主动抛出MyException
System.out.println("正常返回");
}
public static void main(String args[]) {
} System.out.println("这里可执行其它代码"); } }
思考题
1.使用Java Aplication的命令行参数读入两个数据,计算它们的和,然后将和输出。编程自定义例外OnlyOneException与NoOprandException。如果参数的数目不足,显示相应提示信息并退出程序的执行。
System.out.println("finally");
}
System.out.println("No exception?");
}
public static void main(String args[]){
new Ch32 ();
}
}
3、创建自定义异常类程序文件LX33.java,自己给出程序的运行结果。
public class Ch32{
public Ch32(){
try{
int a[] = new int[2];
a[4] = 3;
System.out.println("After handling exception return here?");
}catch(IndexOutOfBoundsException e){
} catch(ArrayIndexOutOfBoundsException f) {
System.out.println("数组索引值大于数组长度的错误!");
}
System.out.println("执行完catch的描述!!!");
}
}
2.运行下面的程序,自己给出程序的运行结果。
import java.io.*;
try {
System.out.println("\n进入监控区,执行可能发生异常的程序段");
mathod(8);
mathod(20);
mathod(6);
}
catch (MyException e) {
System.out.println("\t程序发生异常并在此处进行处理");
System.out.println("\t发生的异常为:"+e.toString());
相关主题