异常处理
异常体系图
异常分量大类
1. 编译异常(需程序员自己处理)
2. 运行异常
五大运行时异常
1. NumberformatException
2. ClassCastException
3. ArrayIndexOutOfBoundsException
4. ArthmeticException
5. NullPointerException
常见写法
// #1
try {
} catch (Exception e) {
e.printStackTrace();
} finally {
}
// #2
try {
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace(); // ...catch
} finally {
}
// #3
try {
} catch () {
}
// #4
try {
} finally {
}
throws 将异常抛出,交给上层处理
异常不处理也可以抛出
void method() throws FileNotFoundException, ArithmeticException, StackOverflowError, ArrayIndexOutOfBoundsException, ClassCastException {
}
方法被重写时,子类异常要是父类异常的子类或者和父类异常一样
throws 和 throw 的区别, throws是异常处理的一种方法,throw是抛出生成的异常对象
一些demo
package edu.chen._exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @author Rw-chen
* @version 0.1
*/
class FileTest {
public static void test() throws Exception {
FileInputStream fs = new FileInputStream("D:\\8069ac814fc0d5c9152ec8e871e70735\\目录说明.txt");
System.out.println(fs);
}
}
class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
}
public class Main {
static Scanner sc = new Scanner(System.in);
static int intputInteger(int age) throws MyException {
if (!(age >= 18 && age <= 120)) throw new MyException("年龄在18到120间");
int ret;
System.out.println("请输入一个整数");
while (true) {
try {
ret = Integer.parseInt(sc.next());
} catch (Exception e) {
System.out.println("输入的不合法,请重新输入");
continue;
}
return ret;
}
}
void method() throws FileNotFoundException, ArithmeticException, StackOverflowError, ArrayIndexOutOfBoundsException, ClassCastException {
}
public static void main(String[] args) throws Exception {
FileTest.test(20);
System.out.println(String.class);
System.out.println("abc".getClass().getName());
System.out.println(intputInteger(0));
int x = 10;
try {
// int a = 10 / 0;
String s = null;
s.getBytes();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
}