1.运行异常
public class Wang {
public static void main(String[] args) {
//ArithmeticException异常:试图除以0
int a=0;
int b=1;
if(a!=0){
System.out.println(b/a);
}
//NullPointerException异常:空指针
String str=null;
if(str!=null){
System.out.println(str.length());
}
//ArrayIndexOutOfBoundsException异常:数组越界
int[] arr=new int[5];
int a2=5;
if(a2<arr.length){
System.out.println(arr[a2]);
}
//强制转型异常
//...
}
}
2.CheckedException已检查异常
2.1使用try-catch处理异常
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Wang {
public static void main(String[] args) {
FileReader reader=null;
try {
reader =new FileReader("e:/a.txt");
char c1=(char)reader.read();
System.out.println(c1);
} catch (FileNotFoundException e) {//子类异常在父类异常前面
System.out.println("step2");
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
System.out.println("step3");
try{
if(reader!=null){
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
2.2 使用throws声明异常
import java.io.FileReader;
import java.io.IOException;
public class Wang {
public static void main(String[] args) throws IOException {
readMyFile();
}
public static void readMyFile() throws IOException {
FileReader reader=null;
reader =new FileReader("e:/a.txt");
char c1=(char)reader.read();
System.out.println(c1);
if(reader!=null){
reader.close();
}
}
}
3.自定义异常
public class Wang {
public static void main(String[] args) {
Person p=new Person();
p.setAge(-10);
}
}
class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
if(age<0){
throw new IllegalAgeException("年龄不能为负数");
}
this.age=age;
}
}
class IllegalAgeException extends RuntimeException{
public IllegalAgeException(){
}
public IllegalAgeException(String msg){
super(msg);
}
}
public class Wang {
public static void main(String[] args) {
Person p=new Person();
p.setAge(-10);
}
}
class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
if(age<0){
try {
throw new IllegalAgeException("年龄不能为负数");
} catch (IllegalAgeException e) {
e.printStackTrace();
}
}
this.age=age;
}
}
class IllegalAgeException extends Exception{
public IllegalAgeException(){
}
public IllegalAgeException(String msg){
super(msg);
}
}
Exception in thread "main" cn.sxt.array2.IllegalAgeException: 年龄不能为负数
at cn.sxt.array2.Person.setAge(Wang.java:21)
at cn.sxt.array2.Wang.main(Wang.java:10)
总结:
1.避免使用异常处理代替错误处理,会降低程序的清晰性,效率低下
2.处理异常不可代替简单测试---只有在异常情况下使用异常处理
3.不要进行小粒度的异常处理---应该将整个任务包装在一个try语句块中
4.异常往往在高层处理