Προγραμματισμός ΙΙ: Εξαιρέσεις και Ισχυρισμοί

Προγραμματισμός ΙΙ

Εξαιρέσεις και Ισχυρισμοί

Εξαιρέσεις

Παράδειγμα ψευδοκώδικα

readFile {
    open the file;
    determine its size;
    allocate that much memory;
    read the file into memory;
    close the file;
}

Χειρισμός ψευδοκώδικα

errorCodeType readFile {
    initialize errorCode = 0;
    
    open the file;
    if (theFileIsOpen) {
        determine the length of the file;
        if (gotTheFileLength) {
            allocate that much memory;
            if (gotEnoughMemory) {
                read the file into memory;
                if (readFailed) {
                    errorCode = -1;
                }
            } else {
                errorCode = -2;
            }
        } else {
            errorCode = -3;
        }
        close the file;
        if (theFileDidntClose && errorCode == 0) {
            errorCode = -4;
        } else {
            errorCode = errorCode and -4;
        }
    } else {
        errorCode = -5;
    }
    return errorCode;
}

Σωστός χειρισμός ψευδοκώδικα

readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
       doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }

Χειρισμός εξαιρέσεων

try {
    some code here
} catch () {
    ;
} finally {
    ;
} …

throws

public void writeList() throws IOException, IndexOutOfBoundsException {...}

throw new

public void checkAmout(int amount) throws NegativeAmoutException {
    if (amount < 0) {
        throw new NegativeAmountException();
    }
}

Τύποι εξαιρέσεων

Παράδειγμα Checked Exception

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public  class testClass {

    public static void main(String args[])  {       
          File file = new File("E://file.txt");
          try {
            FileReader fr = new FileReader(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
       }
}

Παράδειγμα Unchecked Exception

    import java.io.*;
    
    public class ExcepTest {
        public static void main(String[] args) {
            int a[] = new int[2];
            try {
                System.out.println("Access elements three:" + a[3]);
            } catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("Exception thrown :" +e);
            }
            System.out.println("Out of the block");
        }
    }

Χρήση της finally

public class ExcepTest {

   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Ίχνη Στοίβας

Παράδειγμα για Ίχνη Στοίβας

public class ExceptionTesting {

        public static void main(String[] args) {
          try {
                        method1();
                } catch (NullPointerException e) {
                        e.printStackTrace();
                }
        }
        public static void method1() { method11(); }
        public static void method11() { method111(); }
        public static void method111() {
                int[] ar = new int[2];
                System.out.println(ar[3]);
        }

}

Εκτύπωση στοίβας

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at ExceptionTesting.method111(ExceptionTesting.java:11)
    at ExceptionTesting.method11(ExceptionTesting.java:8)
    at ExceptionTesting.method1(ExceptionTesting.java:7)
    at ExceptionTesting.main(ExceptionTesting.java:4)

Δημιουργία εξαιρέσεων

Ισχυρισμοί (1)

Ισχυρισμοί (2)

Διαφορές Ισχυρισμών με Εξαιρέσεις

Παράδειγμα (1)

BankAccount acct = null;

// ...
// Get a BankAccount object
// ...

// Check to ensure we have one
              assert acct != null : "Object Null";

Παράδειγμα (2)

import java.io.IOException;

public class AssertionTest3 {

   public static void main(String argv[]) throws IOException {
      System.out.print("Enter your marital status: ");
      int c = System.in.read();
      switch ((char) c) {
         case 's':
         case 'S': System.out.println("Single"); break;
         case 'm':
         case 'M': System.out.println("Married"); break;
         case 'd':
         case 'D': System.out.println("Divorced"); break;
         default: assert !true : "Invalid Option"; break;
      }

   }
}

Παράδειγμα (3)

    [sgeorgiou@aiolos]$ java -ea AssertionTest3 
    Enter your marital status: n
    Exception in thread "main" java.lang.AssertionError: Invalid Option
        at AssertionTest3.main(AssertionTest3.java:15)

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.