异常处理
语法
异常处理是通过5个关键字来实现
Try 执行可能产生异常的代码
Catch 捕获异常
//根据编号输出课程名称
//0-3,使用异常处理非法编号
public class Course {
public void outPrintCourse (int iNode)throws Exception
{
switch (iNode)
{
case 1:
System.out.println("你选择的是汉语");
break;
case 2:
System.out.println("你选择的是英语");
break;
case 0:
System.out.println("你选择的是数学");
break;
case 3:
System.out.println("你选择的是历史");
break;
default:
throw new Exception();
}
}
public static void main(String[] args) {
Course course = new Course();
try {
course.outPrintCourse(0);
course.outPrintCourse(1);
course.outPrintCourse(2);
course.outPrintCourse(3);
course.outPrintCourse(4);
} catch (Exception e) {
// TODO: handle exception
System.out.println("输入的标号错误");
}
}
}
Finally 无论如何都必须要执行的代码
Throw在代码内处理(异常对象)
Throw 在方法外处理(加在方法名后)抛出的是异常类
package ch02;
public class Exp {
public static int div(int a,int b) { int array[] = new int[a]; //System.out.println(array[a]); return a/b; } public static void main(String[] args) { // TODO Auto-generated method stub try { int res = div(3,0); System.out.println(res); } catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception System.out.println("数组越界了!"); }catch (Exception e) { // TODO: handle exception System.out.println("除数不能为0"); } } }
|
public class Person {
int age;
String sex;
public int getAge() {
return age;
}
public String getSex() {
return sex;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
}
public class TestDemo {
public void setAge(Person p) {
try {
if (p == null) {
throw new Exception();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println("setAge的参数是空指针");
return;
}
Scanner cScanner = new Scanner(System.in);
try {
System.out.println("输入这个人的年龄");
int x = cScanner.nextInt();
if (x < 0 || x > 100) {
throw new Exception();
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("你的年龄不符合要求");
System.out.println("请重新输入");
setAge(p);
}
}
public void setSex(Person p)
{
try {
if (p == null) {
throw new Exception();
}
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("setSex函数的参数是空指针");
return;
}
Scanner scanner = new Scanner(System.in);
System.out.println("输入这个人的性别");
String sex = scanner.next();
try {
if (!sex.equals("男")&&!sex.equals("女")) {
throw new Exception();
}
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("错误的性别输入");
System.out.println("请重新输入");
setSex(p);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p = new Person();
TestDemo testDemo= new TestDemo();
testDemo.setAge(p);
testDemo.setAge(null);
testDemo.setSex(p);
testDemo.setSex(null);
}
}