Arvutiteaduse instituut
  1. Kursused
  2. 2017/18 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (P2NC.01.083)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2017/18 kevad

  • 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
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused