ChapterJAVA异常处理机制.ppt
文本预览下载声明
第6章 Java的异常处理机制; 本章主要内容;异常示例;;import java.io.*;
public class EX_1
{
public static void main(String[] args) throws IOException
{
String number_ch;
int num;
double total=3.25;
System.out.println(有多少个盒子?);
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
number_ch=in.readLine();
num=Integer.parseInt(number_ch);
System.out.println(fgfg:+total*num);
}
};异常;6.1 什么是异常处理机制;6.1.1 什么是错误与异常;6.1.2 异常发生的原因;6.1.3 如何处理异常;抛出异常;;6.2 异常类的层次结构;6.2.1. Exception异常类的子类;(1)RuntimeException类主要包括以下异常子类:;(2)java.io.IOException类的子类有:;(3)Exception异常类的其它子类:;6.2.2 Error错误类的子类;6.3 异常的处理;;例6.1 使用 try…catch语句处理异常的过程。运行结果如图所示: ;public class TC1 {
public static void main(String[] arg3) {
System.out.println(这是一个异常处理的例子\n);
try {
int i=10;
i /=0;
}
catch (ArithmeticException e) {
System.out.println(异常是:+e.getMessage());
}
finally {
System.out.println(finally 语句被执行);
}
}
};例6.2 catch语句中声明的异常类型不匹配的情况。;例6.3 多个catch子句的异常处理。运行结果如图所示。;public class TC3 {
public static void main(String[] args) {
try {
int a=args.length;
System.out.println(\na = +a);
int b=42/a;
int c[]={1};
c[42]=99;
}; catch (ArithmeticException e) {
System.out.println(发生了被 0 除:+e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(数组下标越界:+e);
}
}
};6.3.2 throw语句;例6.4 throw语句的使用,运行结果如图所示。;public class TC5 {
static void throwProcess() {
try {
throw new NullPointerException(空指针异常);
}
catch (NullPointerException e) {
System.out.println(\n在 throwProcess 方法中捕获一个+e.getMessage());
throw e;
}
}
public static void main(String args[]) {
try {
throwProcess();
}
catch (NullPointerException e) {
System.out.println(再次捕获:+e);
}
}
}
;6.3.3 throws子句;1. 抛出异常交其他地方处理异常;下面的例子声明在mathod方法中抛出异常 IllegalAccessException,在调用mathod的main方法里捕获异常。;2. 由方法抛出异常交系统处理;例6.6 throws语句抛出异
显示全部