Java method throwing exception

巧了我就是萌 提交于 2019-12-25 01:27:03

问题


I have a java method which is potent of throwing multiple unchecked exceptions. My question is: do I need to declare it to throw all the the exceptions or Is there any problem if I declare throws Exception only?

Method 1:

public void myMethod() throws Exception1,Exception2,Exception3,Exception4,Exception5
{}

Instead of method 1, can I declare like this?

public void myMethod() throws Exception
{}

回答1:


Yes you can, but ideally people choose a specific type of Exception so that you know which type of "Exceptional" behaviour that block of code is having. Exception is superclass - where other ones are subclasses. If you have unchecked exceptions, i.e. your code does behaviour that can be classified within "Unchecked" Exceptional behaviour, you can use Exceptions class. but otherwise you need Checkedones you mentioned above (may be not all of them).

If you don't understand what different type of exceptions do - try and read this - https://docs.oracle.com/javase/tutorial/essential/exceptions/

This will explain different exceptions and how to use them in your application :)

P.S. For unchecked exceptions, it is NOT required to use throws in your method signature - but using it possibly don't do any harm - at least you are letting people know that you have "An" exception that may be thrown by this code :) [ I am happy to be criticised for that]




回答2:


Yes, you can define. But, method caller will loose some information about the exception thrown. Best practise is to throw specific exception and handle them specifically.




回答3:


You can alway throw the root-exception. If your Exception1,Exception2,,Exception3,Exception4,Exception5 all extend the same exception somewhere in their heritage-tree you can throw this base-exception.

Be aware that exceptions could have a meaning, i.e. show what can go wrong (and give a hint to handle it). Thats especially important if some other developer has to deal with your method.




回答4:


If the exceptions are from another functional area or not in your control, I would handle them (by logging, rollback, cleanup of resources, etc.) and wrap them in my own (Java: checked vs unchecked exception explanation) and throw that.



来源:https://stackoverflow.com/questions/26883510/java-method-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!