10 exceptionsin java
TRANSCRIPT
OOSSE - Java Lecture 112 Apr 2023
Exceptions in Java
OOSSE - Programming with Java
OOSSE - Java Lecture 9 212 Apr 2023
Objectives
In this lecture, we will• Introduce exception handling • Discuss try, catch and finally • Discuss checked and unchecked exceptions
OOSSE - Java Lecture 9 312 Apr 2023
Exceptions
• The Sun Java tutorial defines an exception, an exceptional event, as:“an event that occurs during the execution of a
program that disrupts the normal flow of instructions”
• Exceptions are generated when something goes wrong– try to divide a number by zero
• ArithmeticException– try to access a position past either end of an array
• index is negative, or index >= the array length• ArrayIndexOutOfBoundsException
– attempt to read data of the wrong type, for example with a Scanner object
• InputMismatchException
OOSSE - Java Lecture 9 412 Apr 2023
Exceptions
• Some types of exceptions are unpredictable– They may happen on some runs through the program
but not others– Unpredictable exceptions do not generate compiler
errors
• When they do occur, the program terminates and throws an exception
• For example:Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionEx.main(ExceptionEx.java:6)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
OOSSE - Java Lecture 9 512 Apr 2023
Handling Exceptions
• A program crash can be avoided by handling the exception
• Code that could cause an error is wrapped in a try catch block
Scanner kybd = new Scanner(System.in);
try { int number = kybd.nextInt(); double price = kybd.nextDouble(); } catch (InputMismatchException ime) { System.out.println("Wrong type of input"); System.out.println(ime.toString()); }
OOSSE - Java Lecture 9 612 Apr 2023
Handling Exceptions
• If an exception is generated within the try block then execution immediately jumps to the catch block– the remaining statements in the try block are not
executed
• The catch block can contain code to deal with the problem and handle the exception– or output a message explaining what went wrong
• Regardless of whether an exception occurs, execution continues after the catch block without a crash
• There can be more than one catch block – to deal with different types of exception
• A finally block can exist after all the catch blocks– executed regardless of whether or not an exception
occurs
OOSSE - Java Lecture 9 712 Apr 2023
Handling Exceptions• Code sample:
try { int number = kybd.nextInt(); int answer = number / 0;}catch (ArithmeticException ae){ System.out.println(“Divide by zero");}catch (InputMismatchException ime){ System.out.println("Wrong type of input");} finally { System.out.println("Finally end up here");}
OOSSE - Java Lecture 9 812 Apr 2023
Dealing with an Exception
Scanner kybd = new Scanner(System.in);int num;boolean done = false;while (!done){ try { System.out.println("Please enter an integer"); num = kybd.nextInt(); done = true; } catch (InputMismatchException e){ String invalidInput = kybd.next(); System.out.println("Wrong input, try again"); }}
OOSSE - Java Lecture 9 912 Apr 2023
Unchecked Exceptions
• The examples we have looked at so far are unchecked exceptions– Also known as run-time exceptions
• The exceptions are unpredictable– They may or may not occur– They could happen anywhere
• The compiler does not insist that they are handled– It is not compulsory to use a try-catch block– If an exception occurs outside of a try-catch block
then the program will terminate
OOSSE - Java Lecture 9 1012 Apr 2023
Checked Exceptions
• Some other exceptions are more predictable– An attempt to open a file that does not exist
FileNotFoundException
– An attempt to read beyond the end of a fileEOFException
– Both of these are types of IOException but some other types of exception may also be predictable
• Checked exceptions are predictable• If a method call can generate a checked exception
you must handle it– otherwise will get a compiler error
OOSSE - Java Lecture 9 1112 Apr 2023
Handling File I/O Exceptions
• All code that involves opening and accessing a file must be wrapped in a try-catch blocktry { PrintWriter pw = new PrintWriter("Payroll.txt");
pw.print(name); pw.printf("%6.2f", hourlyPay);
// more file-writing code omitted here pw.close();
} catch(IOException e){ System.out.println("Error writing to file"); }
OOSSE - Java Lecture 9 1212 Apr 2023
Handling File I/O Exceptions
try { Scanner inFile = new Scanner(new File(fileName));
while (inFile.hasNext()) { name = inFile.next(); hourlyPay = inFile.nextDouble(); // more code here to process input } inFile.close();}catch(IOException e) { System.out.println("Error reading from file");}
OOSSE - Java Lecture 9 1312 Apr 2023
What is an Exception?
• The Exception class in Java is the basis for exception handling
• The Exception class is a subclass of the Throwable class– java.lang.Throwable
• The Exception class defines several methods including:– getMessage()– toString()– printStackTrace()
• A method can raise an Exception if something is not right– throw new IOException(“Unable to read data”);
• A method can specify that it may throw an Exception– public String myMethod ( ) throws IOException ….
OOSSE - Java Lecture 9 1412 Apr 2023
Separating Error-Handling Code from "Regular" Code
• 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; }}
OOSSE - Java Lecture 9 1512 Apr 2023
• 2. Propagating Errors Up the Call Stack• method1 { try { • call method2; • } catch (exception e) { • doErrorProcessing; }}• method2 throws exception { • call method3;}• method3 throws exception {• call readFile;} • 3. Grouping and Differentiating Error Types• catch (FileNotFoundException e) { • ...}• catch (IOException e) { ...}
OOSSE - Java Lecture 9 1612 Apr 2023
Summary
In this lecture we have:• Introduced exception handling • Discussed try, catch and finally • Discussed checked and unchecked exceptions