Session 11 |
Throw exception
Before we are going to proceed with the exception handling, let's have a look at how it is possible to break the program flow with own usr friendly message when an exception occurs:
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 to -1, the program flow is interrupted and the following message is printed out:
Exception in thread "main" java.lang.IllegalArgumentException: N cannot be negative! at Example.factor(Example.java:7) at Example.main(Example.java:3)
Session 11 |