Throwing Exceptions When the computer can compile a

  • Slides: 3
Download presentation
Throwing Exceptions When the computer can compile a program but an internal error occurs

Throwing Exceptions When the computer can compile a program but an internal error occurs in execution, it throws an exception. Examples: • Divide by zero. • Attempt to access beyond the end of a string • Type mismatch on input (expects areal value, gets a character, etc. • Etc. 1 public class Cause. Exception { public static void main(String[] args) { 2 int x = 1/0; 3 System. out. println(x); 4 } 5 6 } Console: Exception in thread "main" java. lang. Arithmetic. Exception: / by zero at Cause. Exception. main(Cause. Exception. java: 3) This says the exception was thrown in line 3 of the main method within class Cause. Exception.

Java has a mechanism allowing you to "throw an exception" that: prints an error

Java has a mechanism allowing you to "throw an exception" that: prints an error message prints information about where the error occurred and exits the program // This method computes the factorial of a number // Input: a non-negative integer n // Output: returns the factorial of n, which is the product // of all integers up to n // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120 public static int factorial(int n) { if (n < 0) { throw new Illegal. Argument. Exception("negative n"); } int product = 1; for (int i = 2; i <= n; i++) { product *= i; } return product; } Exception in thread "main" java. lang. Illegal. Argument. Exception: negative n at Factorial. factorial(Factorial. java: 21) at Factorial. main(Factorial. java: 11) Exception occurred at line 11 in main(), where factorial was called

Why would you want to throw an exception? If n < 0 you could

Why would you want to throw an exception? If n < 0 you could just print a message to the user saying what happened. This would be fine at our current level of programming. Problem: If a method is deep within a program it may not know the actual reason for the error. If the error is thrown at that low level it can be caught at a higher level that knows what is going on. (We will look at catching exceptions in a while. ) Also, throwing an exception does not stop the program from running if it is caught. Example: We will soon be using files for input and output. If the user enters a file name but the file is not there, you don’t want the program to stop completely. You might want to give the user a message and ask them to retype the file name. A low level routine (in a system object that you can’t, or shouldn’t, change) would have found the error but has no options other than stopping the program or throwing an exception. It throws the exception which is the right choice.