为什么你不能在Java中抛出并捕获一个Object? [英] Why can you not throw and catch an Object in Java?

查看:129
本文介绍了为什么你不能在Java中抛出并捕获一个Object?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

你能用什么来投入Java?

为什么我不能在Object的引用中使用Exception。
我的意思是考虑以下代码:

Why can't I take an Exception in a reference of Object. I mean consider the following code:

try{.......}
catch(Object ex){.......}

它显示错误,我们在哪里知道任何类的所有对象都可以被Object引用。

It shows an error, where as we knows that it's possible for all the objects of any class to be referenced by Object.

推荐答案

Java语言规范说只有可抛出 s。

The Java Language specification says that only Throwables can be thrown.

http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#44043


每个异常都由类 Throwable 或其子类之一的实例表示;这样的对象可用于将信息从发生异常的点传送到捕获它的处理程序。

Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it.

语言可以已经有不同的定义,但Java倾向于为任何类型的事物定义基本类型,以便以特定方式使用,并定义该基类中的方法以支持常见模式。 Throwable 特别支持链接和堆栈跟踪打印。如果您对异常的唯一理解是它是引用类型,那么就不可能轻易地将异常链接起来。

The language could have been defined differently, but Java tends to define a base type for any kind of thing that is intended to be used in a particular way and defines methods in that base class to support common patterns. Throwable in particular supports chaining and stack trace printing. It would not be possible to chain exceptions as easily if the only thing you knew about an exception was that it was a reference type.

这篇关于为什么你不能在Java中抛出并捕获一个Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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