Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
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
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment