我们可以很简单的认为将异常定义为程序运行时所发生的非正常状况。
我们必须清楚的认知到异常不同于错误,错误发生后程序是不能编译的,而异常一般是再程序编译途中所发生的。
第一种处理方式,异常捕获
try {
for (int i = 0; i < 6; i++) {
System.out.println(arrays[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
第二种处理方式,抛出异常
int x = 1;
int p = 0;
if(p == 0) {
throw new ArithmeticException("分母不可以为零");
} else {
System.out.println(x/p);
}
延伸一下
异常捕获时catch可以有多个,不过一般都是从大到小。
int[] nums = new int[10];
try {
for(int i=0;i<10;i++) {
System.out.println(nums[i]);
}
System.out.println(5/nums[2]);
} catch(ArithmeticException ex) {
System.out.println("除0的算数异常");
} catch(ArrayIndexOutOfBoundsException ex) {
//标明处理的异常类的类名
System.out.println("数组下标越界异常");
} catch(Exception ex) {
System.out.println(ex.toString());
}
System.out.println("程序结束");
而抛出异常一般我们都是应用于类的使用.
package src1;
public class Student {
private String num;
private String name;
private int age;
public void setNum(String num)throws StudentException {
if(num.length()!=12)
{
throw new StudentException("学号不是12位");
//输入具体的问题来产生一个匿名的自定义异常对象,并抛出
}
else
{
if(isAllDigit(num))
{
this.num = num;//只有当所输入的学号参数都是数字字符时才赋给属性学号
}
else
{
throw new StudentException("学号并不全是数字");
}
}
}
//判断字符串中是否全都是数字字符
private boolean isAllDigit(String str)
{
boolean flag=true;
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
if((ch<'0')||(ch>'9'))
{
flag=false;
break;
}
}
return flag;
}
public String getNum() {
return num;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) throws StudentException{
if(age>=16)
{
this.age = age;
}
else
{
throw new StudentException("年龄值必须大于等于16");
}
}
public int getAge() {
return age;
}
public Student(String num,String name,int age)throws StudentException
{
setNum(num);
setName(name);
setAge(age);
}
}
package src1;
public class StudentException extends Exception {
public StudentException (String message) {
super(message);
}
}
//简单的登录代码,用异常处理
package src1;
public class Enroll {
private static final String user = "li";
private static final String cip = "123";
class User extends Exception {
public User(String message) {
super(message);
}
}
class Cip extends Exception {
public Cip(String message) {
super(message);
}
}
public static void login(String name, String num) throws User,Cip {
if(!Enroll.user.equals(name)) {
throw new RuntimeException("名字错误");
}
if(!Enroll.cip.equals(num)) {
throw new RuntimeException("密码错误");
}
System.out.println("登录成功");
}
public static void main(String[] args) {
try {
login("li","123");
} catch (User e) {
e.printStackTrace();
} catch (Cip e) {
e.printStackTrace();
}
}
}
169

被折叠的 条评论
为什么被折叠?



