Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

java - Exception other than RuntimeException

Is there any possibility of exceptions to occur other than RuntimeException in Java? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, there are Three kinds.

Checked exceptions

The compiler will let you know when they can possible be thrown, due to a failure in the environment most likely.

They should be caught, if the program can do something with it, otherwise it is preferred to let them go.

Most of them inherit from

java.lang.Exception

or from

java.lang.Throwable

Although it is better to inherit from the former.

For example:

java.io.IOException

Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

Errors

These are special kinds of exceptions. They SHOULD NOT BE CAUGHT for when they occur means that something really really bad just happened.

All of them inherit from

java.lang.Error

For example:

java.lang.OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

or

java.lang.StackOverflowError

Thrown when a stack overflow occurs because an application recurses too deeply.

RuntimeExceptions

Used to identify programmer failures, rather than resource failures.

A Runtime exception could "normally" be avoided while coding. If you have one most likely you're doing something wrong.

Sometimes runtime exceptions are caught, but, unless you know exactly what you're doing and why, catching them is a bad practice ( again, unless that's exactly what you need )

They inherit from

java.lang.RuntimeException 

For example

java.lang.ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array

or

java.lang.NullPointerException

Thrown when an application attempts to use null in a case where an object is required

About the last two, MOST of the times, they can be avoided by programming carefully and understand what the state of the program is ( does this array have 5 elements? why should I try to access -1 or 6th. Is this reference null? why should I call null.toString() )

Although I have had arguments with guys that claim that all NPE should be caught. Well what can I say.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...