0

Can someone please explain to me the throws Exception part in the following code?

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

   //do something exciting...

}

Thank you in advance.

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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");
}

2 Comments

ahh... so that means it will not handle the exception it will just throw the "error" Am I correct? So that means it is not a good practice?
You may see exceptions as errors, but you can also see them as alternative actions. I'll edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.