自定义一个异常类NoThisSoundException和Player类,在Player的play()方法中使用自定义异常
2017-09-30 13:43
603 查看
7、自定义一个异常类NoThisSoundException和Player类,在Player的play()方法中使用自定义异常
1)NoThisSongException继承Exception类,类中有一个无参和一个接收一个String类型参数的构造方法,构造方法中都使用super关键字调用父类的构造方法。
2)Player类中定义一个play(int index)方法,方法接收一个int类型的参数,表示播放歌曲的索引,当index>10时,paly()方法用throw关键字抛出NoThisSongException异常,创建异常对象时,调用有参的构造方法,传入“您播放的歌曲不存在”。
3)在测试类中创建Player对象,并调用play()方法测试自定义的NoThisSongException异常,使用try…catch语句捕获异常,调用NoThisSongException的getMessage()方法打印出异常信息。
1)NoThisSongException继承Exception类,类中有一个无参和一个接收一个String类型参数的构造方法,构造方法中都使用super关键字调用父类的构造方法。
2)Player类中定义一个play(int index)方法,方法接收一个int类型的参数,表示播放歌曲的索引,当index>10时,paly()方法用throw关键字抛出NoThisSongException异常,创建异常对象时,调用有参的构造方法,传入“您播放的歌曲不存在”。
3)在测试类中创建Player对象,并调用play()方法测试自定义的NoThisSongException异常,使用try…catch语句捕获异常,调用NoThisSongException的getMessage()方法打印出异常信息。
class NoThisSongException extends Exception{ public NoThisSongException(){ super(); } public NoThisSongException(String message){ super(message); } } class Player{ public void play(int index)throws NoThisSongException{ if(index>10){ throw new NoThisSongException("您播放的歌曲不存在"); } System.out.println("正在播放歌曲"); } } public class Test03 { public static void main(String[] args) { Player player = new Player(); try { player.play(13); } catch (NoThisSongException e) { System.out.println("异常信息为: "+e.getMessage()); } } }
相关文章推荐
- wp7使用POST请求Asp.net网页时,HttpWebRequest的BeginGetResponse方法抛出NotSupportException异常的解决方法
- 关于打包自定义标签,并导入项目使用时,出现java.lang.NoClassDefFoundError: JspException异常,解决方法和注意事项!
- 使用JSON报的一个错误java.lang.ClassNotFoundException
- 一个使用c++在lua中创建自定义数据类型的简易方法
- 存储过程中使用RETURN语句返回数值,.Net里用ExecuteScalar方法结果将会导致一个未引用到具体对象的异常
- 调用webservices服务一个异常处理:org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in someth
- 使用网上流传的一个数据库连接池在Proxy.newProxyInstance处引起 java.lang.ClassCastException 问题的解决方法
- 配置SharePoint 2007 过程中引发Microsoft.SharePoint.Upgrade.SPUpgradeException 异常(未能创建配置数据库)的一个解决方法
- 在 Visual Studio 单元测试中使用CallContext 导致的 Unit Test Adapter threw exception: Type is not resolved for member... 异常
- 使用JSON报的一个错误java.lang.ClassNotFoundException
- Velocity使用VelocityLayoutServlet布局之ResourceNotFoundException异常的困扰
- 讨论:一个类的方法应该使用返回值来标识执行状态,还是抛出异常?
- 使用JSON报的一个错误java.lang.ClassNotFoundException
- 在使用Linq to SQL并序列化一个数据对象的时候报System.InvalidOperationException异常,序列化类型XXX的对象时检测到循环引用。
- 使用Oracle连接池错误 Cannot create PoolableConnectionFactory(Io 异常: The Network Adapter could not establish the connection )的解决方法
- 使用MySQL和Hibernate时,出现java.lang.UnsupportedOperationException: Update queries only supported through HQL异常的解决方法
- 使用网上流传的一个数据库连接池在Proxy.newProxyInstance处引起 java.lang.ClassCastException 问题的解决方法
- Java访问DotNet平台WCF服务,使用自定义对象如IDictionary做参数时,抛出"Did not understand MustUnderstand"异常
- 通知栏Notification使用自定义视图方法(显示一个进度条ProgressBar)
- 对自定义函数建立索引时抛异常--ORA-30553: 函数不能确定(ORA-30553: The function is not deterministic)解决方法