import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; class Feil { // Metoden delTall() kan føre til forskjellige feil. // To typer: // checked - feil som MÅ håndteres: // FileNotFoundException // unchecked - feil som ikke må håndteres: // ArithmeticException, ArrayIndexOutOfBoundsException, // NumberFormatException // For å håndtere en feil har vi to muligheter: // 1. Kaste feilen videre, altså: // public int delTall() throws Exception {} // 2. FAKTISK håndtere feilen med en try/catch-blokk // som i eksempelet under. public int delTall() { // Ber bruker om to tall fra terminal. Scanner input = new Scanner(System.in); System.out.print("Skriv inn to tall: "); String linje = input.nextLine(); String[] listeTall = linje.split(" "); //Fanger opp alle eventuelle feil. try { File fil = new File("text.txt"); Scanner skan = new Scanner(fil); int tall1 = Integer.parseInt(listeTall[0]); int tall2 = Integer.parseInt(listeTall[1]); int svar = tall1 / tall2; return svar; } catch(FileNotFoundException e){ System.out.println(e); } catch(ArithmeticException e){ return delTall(); } catch(ArrayIndexOutOfBoundsException e){ return delTall(); } catch(NumberFormatException e){ return delTall(); } catch(Exception e){ System.out.println(e); } return -1; } }