8. IO stream + ioexception - Exceptions An Exception is an...

This preview shows page 1 - 3 out of 6 pages.

Exceptions An Exception is an object that describes an unusual or erroneous situation. -If an exception is ignored by the program, the program will terminate and produce an appropriate message. Example: -------------------------------------------------------------------------------------- public class DividingByZero { //----------------------------------------------------------------- // Deliberately divides by zero to produce an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } } ------------------------------------------------------------------------------------ Output Exception in thread “main” java.lang.ArithmeticException: / by zero at DividingByZero.main(DividingByZero.java:11) -------------------------------------------------------------------------------------- The call stack trace : indicating where the exception occurred. This exception was produced by the line “System.out.println (numerator / denominator);” because it divides by zero. At this point, the program is terminated and the next line is never executed. 1
We can avoid the termination of a program caused by an exception by using: try statements. Try statements try { // the line that throws the exception is included here } catch ( //put the exception object produced in try , e.g., IOException ) { } finally { // the statements inside of finally

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture