9.1.1异常概述
1、认识异常
异常是指程序运行过程中发生的不正常事件,它会中断程序的运行。
2、java异常体系结构
9.1.2java异常处理机制
1、异常处理。
方法中含有未处理的检查性异常,必须在签名中声明
2、使用throws声明抛出异常。
如果一个方法没有捕获一个检查性异常,那么这个方法需要使用throws关键词
public class Person {
private String name = ""; // 姓名
private int age = 0; // 年龄
private String sex = "男"; // 性别
public void setSex(String sex) throws Exception {
if ("男".equals(sex) || "女".equals(sex))
this.sex = sex;
else {
//自定义抛出异常
throw new Exception("性别必须是男或者女!");
}
}
}
3、使用throw抛出异常。
public void setAge(int age)throws wrongAgeException {
if(age<0||age>120){
throw new wrongAgeException("年龄异常");
}
this.age = age;
}
4、使用try-catch处理异常。
public class Test1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try{
System.out.println("请输入被除数:");
double num1=sc.nextInt();
System.out.println("请输入除数:");
double num2=sc.nextInt();
System.out.println(num1+"/"+num2+"="+num1/num2);
}catch(ArithmeticException e){
System.err.println("除数不能为0");
e.printStackTrace();//打印堆栈错误信息
System.out.println(e.getMessage());
}catch(InputMismatchException e){
System.err.println("被除数和除数必须为整数");
}catch(Exception e){
System.err.println("出现错误,非法操作");
}finally {
System.out.println("感谢使用本程序!");
}
}
}
e.printStackTrace() ; //打印堆栈异常信息。
e.getMessage();
5、使用try-catch-finally块处理异常。
6、使用多重catch
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
7、自定义异常。
public class wrongAgeException extends Exception {
public wrongAgeException(String message){
super(message);
}
}
public class wrongNameException extends Exception {
public wrongNameException(String message){
super(message);
}
}
public class Exception1 {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age)throws wrongAgeException {
if(age<0||age>120){
throw new wrongAgeException("年龄异常");
}
this.age = age;
}
public void setName(String name)throws wrongNameException {
if(name.equals("马化腾")){
throw new wrongNameException("马化腾正在提刀来的路上");
}
this.name = name;
}
public static void main(String[] args) {
Exception1 s=new Exception1();
try {
s.setName("马化腾");
} catch (wrongNameException e) {
e.printStackTrace();
}
try {
s.setAge(-1);
} catch (wrongAgeException e) {
e.printStackTrace();
}
System.out.println(s.getAge());
}
}