Session 11 |
Throw exception
To demonstrate exception, including how an exception object is created and thrown, consider the following example:
static int factor(int n) { if (n < 0) throw new IllegalArgumentException("N cannot be negative!"); // an exception is thrown int result = 1; for (int i = n; i > 1; i--) result = result * i; return result; }
If n equals -1, there is no return value. The value thrown, in this case new IllegalArgumentException("N cannot be negative!")
, is called an exception. The execution of a throw statement is called throwing an exception. The exception is an object created from an exception class. In this case, the exception class is IllegalArgumentException
. The constructor IllegalArgumentException(String str)
is invoked to construct an exception object, where str is a message that describes the exception. This information is known as a stack trace. The stack trace of the case above is:
Exception in thread "main" java.lang.IllegalArgumentException: N cannot be negative! at Example.factor(Example.java:7) at Example.main(Example.java:3)
Pay attention! If we only print the stack trace, this does not handle the exception nor protect the program from crashing. Exception handling is done in the try
and catch
block. Check the next page :)
Session 11 |