抛出throw异常和捕捉catch异常的问题?

Patrick_DK 2001-09-10 01:13:18
最近学到JAVA的异常处理,有三个问题搞不懂,请教一下大家。
一。书上说抛出THROW异常是为了让调用这个方法的方法来处理异常情况。如下代码所示:
static void arraytest(int i)
*throws ArrayIndexOutOfBoundsException
{
写一个数组下标溢出错误
}

public static void main(String args[])
{
try
{
arraytest(i);//调用这个有错误的方法
}
catch(ArrayIndexOutOfBoundsException e)
{
输出提示
}
}
这段代码我运行了一下,发现要不要带*号的那条THROWS抛出异常,运行结果都一样的。请问这个抛出THROW异常到底有什么实际的意义啊?我不用它,也可以用try_cacth_finally来处理嘛?

二。如何写用户自定义的异常?

三。怎么处理自定义的异常啊?

二、三题请用具体的代码举个例子,谢谢!!
...全文
1000 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
vbstudent 2002-01-29
  • 打赏
  • 举报
回复
记号
contributor 2001-12-20
  • 打赏
  • 举报
回复
the key is the concept of "unchecked". You just throw a unchecked exception. therefore, you do not need to add Throws clause after your method name. If you throw a checked exception, you must add Throws clause after your method name.
小凤哥 2001-12-20
  • 打赏
  • 举报
回复
private void a() throws xxException {} //do nothing

private void b() throws xxException {//will success
a();
}

private void c(){ //will success
try{
a();
}catch(xxException ex){}
}

private void d(){ //will not success
a();
}
Patrick_DK 2001-12-19
  • 打赏
  • 举报
回复
最好谁能提供一个小的关于throw+throws+catch的程序看看,这样可能比较容易彻底搞懂
Patrick_DK 2001-12-19
  • 打赏
  • 举报
回复
pushpushpush
Patrick_DK 2001-12-03
  • 打赏
  • 举报
回复
那你们看看我这样理解对不

语句throw是抛出异常,也就是在使用throw语句的地方抛出,由这个方法来处理
语句throws是将异常抛向调用带throws语句的方法的方法,由它来处理

那么还有个问题,所有异常都遵守这个格式吗?因为我在SL275里看到下面这句话:
"You do not need to handle or declare runtime exceptions or errors."
Patrick_DK 2001-12-03
  • 打赏
  • 举报
回复
也就是说编程的时候不用考虑RuntimeException喽?
zych72 2001-12-03
  • 打赏
  • 举报
回复
语句throws描述本方法有可能会抛出异常。
"You do not need to handle or declare runtime exceptions or errors."
意思是你不需要定义活处理运行时异常,JVM会替你做的

baoyc 2001-09-10
  • 打赏
  • 举报
回复
static void arraytest(int i)
*throws ArrayIndexOutOfBoundsException
{
try
{
写一个数组下标溢出错误
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("err in function");
}
}

public static void main(String args[])
{
try
{
arraytest(i);//调用这个有错误的方法
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("err out function");
}
}
你再试一下,看看有什么不同,就知道该怎么用了。
sharetop 2001-09-10
  • 打赏
  • 举报
回复

正是如此,你看一下throws的位置也明白了,throws是跟在方法名后的,说明是这个方法要抛出给其它方法处理的违例。而如果你在方法内要抛出一个违例,用throw new Exception()句子。

至于二三题,很简单的一个例子是 throw new Exception("例子错误");

你catch到它后,可以用 ex.getMessage()得到这个字串。

或是你自定义一个伟例,如
class myException extends Exception
{
public myException(String msg){
super(msg);
}
}

这是一个最简单的违例,如果你想加入其它信息什么的,就扩充它。

forest 2001-09-10
  • 打赏
  • 举报
回复
1.throw和throws的区别在于,throw用于抛出异常,throws用于再抛出。抛出很好理解,就不解释了,再抛出的意思是,对于方法体内的异常,不想在该方法体内处理,就再次抛出,让调用他的方法来处理。
在你所举的例子中,之所以看不到加与不加throws的区别,因为你的方法
static void arraytest(int i)所抛出的是runtimeException,而且在MAIN方法中CATCH了。
试试看抛出一条IOException,如果在static void arraytest(int i)中没有catch,也不用throws再抛出的话,编译都通不过。
2.关于写和处理自定义异常,书上一般都有例子的,实在找不到再说吧

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧