您的位置:首页 > 编程语言 > Java开发

Java高级语法笔记-自定义异常类

2018-01-09 10:01 447 查看
自定义异常类

继承Exception,自定义异常类: 异常类要能够描述错误信息

比如,非法字符异常 IllegalCharException应该把非法字符的位置带上。

throws多种异常

throws用于声明本函数可能产生的异常的种类

void parse(String s) throws IllegalCharException,BadFromatException{

}

各异常类以逗号分隔

异常的匹配

根据抛出的异常对象的类型,从前往后匹配catch语句。

- 若匹配成功,则其他的catch不再匹配.

- 若全不匹配,则继承向上层函数抛出。

异常的匹配

怎么才算是匹配成功?假设抛出的对象类型为EA

catch(EX e)

{

}

如果EA与EX类型相同,或是EX的子类,则匹配成功.怎么抓获所有类型的异常?

catch( Exception e)

{

}

由于Exception类是所有异常的父类,所以用这个肯定能捕获异常。(相当于default处理)

代码如下:

BadFormatException.java

package my;

public class BadFormatException extends Exception
{
String reason;
public BadFormatException(String reason) {
this.reason=reason;
}
@Override
public String getMessage()
{
return "格式错误("+reason+")";
}
}

BadRangeException.java
package my;

public class BadRangeException extends Exception
{
String reason;
public BadRangeException(String reason) {
this.reason=reason;
}
@Override
public String getMessage()
{
return "范围错误("+reason+")";
}

}

Date.java
package my;

public class Date
{
public int year,month,day;
public void parse(String dateStr) throws IllegalCharException,BadFormatException,BadRangeException
{
//检测非法字符
for(int i=0;i<dateStr.length();i++) {
char ch=dateStr.charAt(i);
if(ch>='0'&&ch<='9') ;
else if(ch=='-');
else throw new IllegalCharException(i);
}
//检测分割符
int p1=dateStr.indexOf("-");
if(p1<0) throw new BadFormatException("找不到第1个横杠!");
int p2=dateStr.indexOf("-",p1+1);
if(p2<0) throw new BadFormatException("找不到第2个横杠!");

//检测年月日的长度
String s1=dateStr.substring(0, p1);
String s2=dateStr.substring(p1+1, p2);
String s3=dateStr.substring(p2+1);
if(s1.length()!=4) throw new BadFormatException("格式不对:年份错误!");
if(s2.length()!=1&&s2.length()!=2) throw new BadFormatException("格式不对:月份错误!");
if(s3.length()!=1&&s3.length()!=2) throw new BadFormatException("格式不对:日份错误!");

this.year=Integer.valueOf(s1);
this.month=Integer.valueOf(s2);
this.day=Integer.valueOf(s3);

//有效性检测
if(month<0||month>12) throw new BadRangeException("数据无效:月份不能为"+month);
if(day<0||day>31) throw new BadRangeException("数据无效:日期不能为"+day);

}
@Override
public String toString()
{
return year+"年"+month+"月"+day+"日";
}
}


HelloWorld.java
package my;

public class HelloWorld
{
public static void main(String[] args)
{
Date d=new Date();
try {
d.parse("2016B-12-1");
System.out.println("日期为:"+d.toString());
}catch(IllegalCharException e) {
System.out.println(e.getMessage());
}
catch(BadFormatException e) {
System.out.println(e.getMessage());
}
catch(BadRangeException e) {
System.out.println(e.getMessage());
}
catch(Exception e) {

}
}

}

IllegalCharException.java
package my;

public class IllegalCharException extends Exception
{
int position=0;
public IllegalCharException(int pos) {
this.position=pos;
}
@Override
public String getMessage()
{
return "非法字符("+position+")";
}
public int getPosition() {
return position;
}
}

运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 异常处理