在这种情况下应该如何处理异常 [英] How should I handle Exception in this scenario

查看:197
本文介绍了在这种情况下应该如何处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在serachBook()中,如果在ArrayList中找到了这本书,它将返回书对象如果没有找到它将抛出自定义异常BookNotFound。



问题1:如果它只返回null并且在调用代码时检查返回值为null或抛出自定义异常BookNotFound。



目前我相信BookNotFound是合适的,目前正在做。但是我还发现一个困难:在addbook()中,我首先调用searchBook()来看书已经存在,如果没有添加这本书。但是如果书不存在searchBook()抛出BookNotFound。消息2:如何处理addBook()中的searchBook()抛出的异常,因为为了将book()插入到列表中,BookNotFound异常必须发生。所以我应该写空Catch(BookNotFound e){}?



什么可以更好的OO练习?

解决方案

如果没有找到书并在方法文档中陈述,您应该返回 null



异常 throwing is昂贵的操作也非常适合特殊情况(例如您在 searchBook()中传递null的书名称方法


Hi there I am learning OOP by writing a dummy Library management project in Java.

In serachBook(), if book is found in ArrayList, it returns book object, if not found it throws custom exception BookNotFound.

Question 1: Should it just return null and check the returned value at calling code for null or throw custom exception BookNotFound.

Currently I believe BookNotFound is appropriate and am currently doing it. However I am finding one more difficulty: In addbook(), I first call searchBook() to see book already exist, if not it adds the book. However if book doesnt exist searchBook() throws BookNotFound.

Qestion 2: How should I handle this exception thrown by searchBook() in addBook(), since in order to addBook() to insert book in a list, BookNotFound exception must occur. So should I write empty Catch(BookNotFound e){} ?

What could be better OO practice?

解决方案

You should return null if it doesn't find book and state it in method document,

Exception throwing is costly operation also it is well suited in exceptional case (like book name you passed null in searchBook() method

这篇关于在这种情况下应该如何处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆