Handling Exceptions in Programming

Handling Exceptions in Programming
Slide Note
Embed
Share

Learn how to effectively handle exceptions in your programs by implementing try-catch blocks. Discover common scenarios where exceptions occur, such as input mismatch errors and file-not-found exceptions. Find out how to create custom exception classes for specific error handling. Enhance the robustness of your code and ensure graceful recovery from unexpected errors.

  • Programming
  • Exceptions
  • Error Handling
  • Try-Catch Blocks
  • Custom Exceptions

Uploaded on Feb 19, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Exceptions Throwing, Catching Defining

  2. Outcomes Find the exception that crashed a program find where it happened in your code Write a try-catch block to catch exceptions your program might throw Design and place try-catch blocks so your program recovers gracefully Create your own Exception class

  3. Exceptional Circumstances Reading numbers from user User types in a word not the sort of thing we expected program crashes Enter a number: 20 Enter another number: done Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) see SumNumbers.java

  4. Exceptional Circumstances Reading file name from user User gives name of a file that doesn t exist can t open that file for input program crashes Enter the name of a file and I will sum its numbers: noSuchFile.txt Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20) see SumUsersFile.java

  5. Exceptions Our Scanner has thrown an exception Exception in thread main java.util.InputMismatchException Exception in thread main java.io.FileNotFoundException It ran into an error it couldn t fix program crashed eventually!

  6. What Exception? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

  7. Where? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

  8. Where??? Methods call other methods which may call other methods in turn One method throws the exception error message shows whole stack of calls main nextDouble next Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) throwFor

  9. Look for Your Program Many of the methods don t belong to you you can t do anything about them Some of the methods are yours that s where you can do something Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) line 26 of SumNumbers.java

  10. Exercise Where did this exception get thrown from? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at csci1227.Scanner.nextInt(Scanner.java:169) at ArraySearcher.search(ArraySearcher.java:178) at ArraySearcher.main(ArraySearcher.java:58) What methods were called? What line(s) of your program are relevant?

  11. Exception Hierarchy Exception IOException RuntimeException EOFException ClassCastException FileNotFoundException ConcurrentModificationException IndexOutOfBoundsException IllegalArgumentException ArrayIndexOutOfBoundsException NoSuchElementException StringIndexOutOfBoundsException NullPointerException InputMismatchException

  12. Throwing Exceptions Throw an exception when errors happen and you can t deal with it properly Throw an appropriate type of exception illegal argument IllegalArgumentException out of bounds IndexOutOfBoundsException bad time for request IllegalStateException If necessary, make your own exception type extend RuntimeException

  13. Setters Throwing Exceptions Client tries to set property to illegal value length & width of rectangle must be >= 0 public void setWidth(double newWidth) { // object to negative widths if (newWidth < 0) { String message = "Illegal width: " + newWidth; throw new IllegalArgumentException(message); } // new width OK make the change width = newWidth; }

  14. The throw Command Command to throw an exception is throw throw new IllegalArgumentException(message); Exception to throw usually created there throw new IllegalArgumentException(message); Exception constructor given a message String message = "Illegal width: " + newWidth; throw new IllegalArgumentException(message); message is printed out if program crashes

  15. Exercise Rewrite the following constructor to throw an exception if either argument is negative public Rectangle(double reqWidth, double reqHeight) { if (reqWidth >= 0) { width = reqWidth; } else { width = 0; } if (reqHeight >= 0) { height = reqHeight; } else { height = 0; } }

  16. General Principle Exceptions are thrown by data type objects Scanner, FileInputStream, Rectangle, objects that get asked to do things and might find themselves unable/unwilling Not usually thrown by programs programs are in control, giving orders responsible for dealing with problems so far, we haven t been dealing with exceptions it s time we started

  17. Catching Exceptions try-catch block try { } catch(ExceptionClassexceptionObject) { // code to handle the exception } Try to do this, and if something goes wrong, do this to deal with it // code that may throw an exception

  18. Catching Exceptions For catching InputMismatchException inside the number-reading loop try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException ime) { System.out.println("That's not a number!"); break; // exit from loop } // may throw an exception Note: it s a parameter! see CatchInputMismatch.java

  19. When No Exceptions Occur while (num >= 0.0) { sum += num; System.out.print("Enter another number: "); try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException e) { System.out.println("That's not a number!"); break; // exit from loop } }

  20. When An Exception Occurs while (num >= 0.0) { sum += num; System.out.print("Enter another number: "); try { num = kbd.nextDouble(); // doesn t even get to finish! kbd.nextLine(); } catch(InputMismatchException e) { System.out.println("That's not a number!"); break; // exit from loop } }

  21. Notes InputMismatchException part of java.util needs to be imported along with Scanner import java.util.Scanner; import java.util.InputMismatchException; Our program exits the loop because of the break command normally would continue on inside the loop (or whatever comes after the catch block)

  22. When an Exception Occurs Code in try block gets skipped right out from where the exception occurred // read an integer and save it in num num = kbd.nextInt(); // skip the rest of the input line kbd.nextLine(); if next thing isn t an int, NONE of that happens doesn t read an integer (no integer there to be read!) doesn t save anything in num (num unchanged!) doesn t skip rest of line

  23. Dealing with Exceptions After catching the exception, the body of the catch block is executed does whatever it says to do print a message; break out of a loop Question to ask yourself: what do I want my program to do when it catches this exception?

  24. What Do I Want to Do? Reading int values; non-int value entered try { num = kbd.nextInt(); } catch (InputMismatchException ime) { end the loop? break; skip invalid data? kbd.next(); } but if you skip, what else might go wrong?

  25. Exercise What happens with the following code when the user enters a non-number? num = kbd.nextDouble(); while (num >= 0.0) { sum += num; System.out.print("Enter another number: "); try { num = kbd.nextDouble(); } catch(InputMismatchException e) { System.out.println("That's not a number!"); kbd.nextLine(); } } kbd.nextLine(); kbd.nextLine(); What goes wrong? How might we fix it?

  26. Bigger Try Blocks Enter a word instead of the first number program crashes! Catch blocks only catch exceptions from the corresponding try blocks exceptions from outside don t get caught Try block can be as big as you want so long as it stays inside the method

  27. A Loop inside a try Block Exception stop reading numbers even if it s the first number! int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } } catch (InputMismatchException ime) { } System.out.println("The sum is " + sum); What does the catch block do here?

  28. Exercise Revise the code so that the sum is only printed if the loop ends normally that is, by the user entering a negative number int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } } catch (InputMismatchException ime) { } System.out.println("The sum is " + sum); NOTE: You don t need to add any code. Just move a piece of it!

  29. Our Own Exception Classes Usually use a built-in exception class e.g. IllegalArgumentException Can create our own exception classes if none of the available ones is exactly right or want to distinguish different problems We will extend RuntimeException extending Exception leads to complications or some other suitable RuntimeException e.g. IllegalArgumentException

  30. Our Own Exception Class NotEnufMilkException represents not having enuf milk public class NotEnufMilkException extends RuntimeException { public NotEnufMilkException() { } public NotEnufMilkException(String message) { super(message); } } just the two constructors see NotEnufMilkException.java

  31. Our Own Exception Classes Name ends with Exception just so we re clear about what it is! Consists of two constructors default constructor does nothing well, calls super(); but you remembered that, right? constructor with String parameter calls super with that String super(message); sets the message property of this Exception

  32. Another Exception Class NotEnufCookiesException public class NotEnufCookiesException extends RuntimeException { public NotEnufCookiesException() { } public NotEnufCookiesException(String message) { super(message); } } What exactly is the difference between this exception class definition and the previous one? see NotEnufCookiesException.java

  33. Catching Different Exceptions Can have more than one catch block each has a different exception it catches try { } catch(NotEnufMilkException e) { } catch(NotEnufCookiesException e) { } if an exception is thrown, it goes to the matching catch block if no matching block, it keeps going until it is caught, or until it gets out the top (crash!) see RoomReports.java

  34. More Constructors Every Exception class should have constructors for () and (String) every built in Exception class does Can add more of our own assignment number is an int public NoSuchAssignmentException(int asgn) { super(Integer.toString(asgn)); } need to call super(String) no super(int)!

  35. Questions?

More Related Content