自定义异常类

作者在 2010-05-16 15:03:32 发布以下内容
package com.yds.text4;
class MyException extends Exception
{
String str1;
MyException(int m)
{
str1=m+"出现错误 可能造成的原因是取值大于1000";//出始化异常信息
}
public void showStr1()
{
System.out.println(str1);
}
}
class Student
{
public void speak(int m) throws MyException
{
if(m>1000)
{
MyException exception=new MyException(m);//如果传过去的值大于1000则抛出自定义异常
throw exception;
}
else
System.out.println(m);
}
}
public class Test5MyException
{
public static void main(String agrs[])
{
int m;
Student stu1=new Student();
m=987;
try
{
stu1.speak(m);
m=1332;
stu1.speak(m);
}
catch(MyException e)
{
e.showStr1();
}
}
}
专业文章 | 阅读 655 次
文章评论,共0条
游客请输入验证码
浏览275879次