开发者

Java Exception Help

Can someone please explain to me the throws Exception part in t开发者_C百科he following code?

public static void main(String args[]) throws Exception {

   //do something exciting...

}

Thank you in advance.


it means the function main(String[]) can throw any sub-type of Exception. in Java, all exceptions thrown by a method(except RunTimeException) must be explicitly declared.
that means every method using main(String[]) will have to take care (try,catch) Exception, or declare itself as throwing Exception as well.


Exceptions are a way Java uses to act when something unexpected happened. For example, if you want to read/write from/to a file, you have to handle IOException that will be thrown if there is a problem with the file.

A little example to explain that to you:

Let's take a method called method1() that throws an exception:

public void method1() throws MyException {
  if (/* whatever you want */)
    throw new MyException();
}

It can be used in two ways. The first way with method2() will simply toss the hot potatoe further:

public void method2() throws MyException {
  method1();
}

The second way with method3() will take care of that exception.

public void method3() {
  try {
    method1();
  }
  catch (MyException exception) {
  {
    /* Whatever you want. */
  }
}

For more information about exceptions, http://download.oracle.com/javase/tutorial/essential/exceptions/ should help.


EDIT

Let's say we want to return the containt of a value in this array (which is the square of the entered number): int[] squares = {0, 1, 4, 9, 16, 25}; or 0 if the number (input) is too big.

Pedestrian Programming:

if (input > squares.length)
  return 0;
else
  return squares[input];

Exception Guru Programming:

try {
  return squares[input];
}
catch (ArrayIndexOutOfBoundException e) {
  return 0;
}

The second example is cleaner, for you can also add another block (and another again) after that, so that every possible problem is fixed. For example, you can add this at the end:

catch (Exception e) { // Any other exception.
  System.err.println("Unknown error");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜