




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















[CS1020 Lecture 8 : Exceptions]
Occurs when the rule of the language is violated Detected by compiler
Occurs when the computer detects an operation that cannot be carried out (eg: division by zero; x/y is syntactically correct, but if y is zero at run-time a run- time error will occur)
Occurs when a program does not perform the intended task
[CS1020 Lecture 8 : Exceptions]
public static int factorial (int n) { int ans = 1; for (int i = 2; i <= n; i++) ans *= i; return ans; }
Should we terminate the program? public static int factorial (int n) { if (n < 0 ) { System.out.println("n is negative"); System.exit( 1 ); } //Other code not changed } System.exit ( n ) terminates the program with exit code n. In UNIX, you can check the exit code immediately after the program is terminated, with this command: echo $?
[CS1020 Lecture 8 : Exceptions]
Exception mechanism consists of two components:
Note that the preceding example of using exception for ( n < 0) is solely illustrative. Exceptions are more appropriate for harder to check cases such as when the value of n is too big, causing overflow in computation. [CS1020 Lecture 8 : Exceptions]
[CS1020 Lecture 8 : Exceptions]
[CS1020 Lecture 8 : Exceptions]
public static int factorial (int n) throws IllegalArgumentException { if (n < 0 ) { IllegalArgumentException exObj = new IllegalArgumentException(n + " is invalid!"); throw exObj; } int ans = 1 ; for (int i = 2 ; i <= n; i++) ans *= i; return ans; } This declares that method factorial() may throw IllegalArgumentException Actual act of throwing an exception (Note: ‘throw’ and not ‘throws’ ). These 2 statements can be shortened to: throw new IllegalArgumentException(n + " is invalid!"); [CS1020 Lecture 8 : Exceptions]
[CS1020 Lecture 8 : Exceptions]
Keep retrying if n < 0 [CS1020 Lecture 8 : Exceptions]
[CS1020 Lecture 8 : Exceptions]