Java方法抛出异常 [英] Java method throwing exception

查看:155
本文介绍了Java方法抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java方法,它有助于抛出多个未检查的异常。我的问题是:我需要声明它抛出所有的异常或是否有任何问题,如果我声明仅抛出异常



方法1:

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

而不是方法1,我可以这样声明吗?

  public void myMethod()throws Exception 
{}


解决方案

是的,你可以定义。但是,方法调用者将会丢失一些有关引发的异常的信息。最佳做法是抛出特定的异常并专门处理。


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
{}

解决方案

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.

这篇关于Java方法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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