与大家分享一个自定义异常的案例,刚学习异常的同学可以看一下。
package st2017;
public class CustomException {
public static void main(String[] args) {
Person per;
try{
per = new Person("Anna",39);
String name = per.getName();
}catch(TempException e)
{
System.out.println(e);
}finally
{
System.out.println("--------------");
}
}
}
class TempException extends Exception
{
private double t;
public void setT(double t) {
this.t = t;
}
public double getT() {
return t;
}
TempException(String msg)
{
super(msg);
}
}
class Person
{
private String name;
private double t;
Person(String name,double t)throws TempException
{
if(t>38.0)
{
TempException e = new TempException(name+",体温"+t+",非典疑似病例");
e.setT(t);
throw e;
}
this.name = name;
this.t = t;
}
public String getName()
{
return this.name;
}
public double getT() {
return t;
}
}