Mastering Exception Handling in Java

recitation 2 n.w
1 / 17
Embed
Share

Learn how to effectively handle exceptions in Java programming to prevent code crashes and improve error management. Understand the hierarchy of exception classes, superclass Throwable, handling errors without exceptions, and throwing and catching exceptions with real-world examples.

  • Java
  • Exception Handling
  • Error Management
  • Programming

Uploaded on | 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. Recitation 2 Exception handling

  2. Exceptions Exceptions make your code crash public static void main(String[] args) { System.out.println(args[0]); } public static void main(String[] args) { System.out.println(8 / 0); } public static void main(String[] args) { System.out.println(null.toString()); }

  3. Exceptions What could happen without exceptions? public static double getAverage(double[] b) { double sum = 0; for (int i = 0; i < b.length; i++) { sum += b[i]; } return sum / b.length; } If b.length is 0, what should be returned? - Infinity - special int - Integer.MAX_VALUE? 2110? 0?

  4. Exceptions Superclass of exceptions: Throwable Throwable@x2 When some sort of exception occurs, an object of class java.lang.Throwable (or one of its subclasses) is created and thrown --we explain later what throw means. Throwable / by zero detailMessage Throwable() Throwable(String) getMessage() The object has 1. Field to contain an error message 2. Two constructors 3. Function to get the message in the field

  5. Exceptions Superclass of exceptions: Throwable Two subclasses of Throwable exist: Error: For errors from which one can t recover don t catch them Exception: For errors from which a program could potentially recover it s ok to catch them Error@x2 Exception@x2 Throwable Throwable / by zero detailMessage / by zero detailMessage Throwable() Throwable(String) getMessage() Throwable() Throwable(String) getMessage() Error Exception Error() Error(String) Exception() Exception(String)

  6. Exceptions A Throwable instance: ArithmeticException There are so many different kinds of exceptions we need to organize them. ArithmeticException@x2 Throwable detailMessage / by zero Throwable Exception Exception Error RuntimeException RuntimeException ArithmeticException ArithmeticException

  7. Exceptions Throwing an exception When an exception is thrown, it is thrown to the place of call, which throws it out further to where that method was called. The code that called main will catch the exception and print the error message 1 2 3 4 5 6 7 8 9 10 11 12 13 class Ex { static void main( ) { second(); } AE static void second() { third(); } Method call: main(new String[] {}); Console: java.lang.AE: / by zero at Ex.third(Ex.java:11) at Ex.second(Ex.java:7) at Ex.main(Ex.java:3) AE Static void third() { int c= 5/0; } AE } AE = ArithmeticException

  8. Exceptions Decoding the output from an exception public static void main(String[] args) { int div= 5/0; } 1 2 3 Exception that is thrown message Exception in thread "main" java.lang.ArithmeticException: / by zero at Animal.main(Animal.java:2) line number called method

  9. Try statement: catching a thrown exception To execute the try statement: try { Execute the try-block. If it finishes without throwing an exception, fine. code (this is the try-block) } catch (MyException ae) { code (this is the catch-block) } If the try-block throws a MyException object, catch it (execute the catch block); else throw it out further. S; (code following the try statement) If the exception was caught, execution proceeds to the code S following the try-statement. ae is like a parameter. When the catch-block catches a thrown object, ae contains the object

  10. Exceptions throw keyword: Forcing a crash Why might I want to crash the application? class Integer { /** Parse s as a signed decimal integer. * Throw a NumberFormatException * if not possible */ public static int parseInt(String s){ parseInt( 42 ) -> 42 parseInt( Sid ) -> ??? if (can t convert to int){ throw new NumberFormatException(); } ... } }

  11. Demo 1: Read an Integer Ask the user to input an int Try to convert user input to an int If an exception is thrown, catch it and ask for more input

  12. Exceptions Exercise 3: Illegal Arguments Create class Person with two fields, name and age. Throw an IllegalArgumentException instead of having preconditions when given a null name or a non- positive age.

  13. Exceptions How to write an exception class /** An instance is an exception */ public class OurException extends Exception { /** Constructor: an instance with message m*/ public OurException(String m) { super(m); } /** Constructor: an instance with no message */ public OurException() { super(); } }

  14. Exceptions Exceptions throws clause public static void second() { String line= kyboard.readLine(); } Unhandled exception type IOException You may get an error message like the yellow one above. In that case, insert a throws clause as shown below. public static void second() throws IOException { String line= kyboard.readLine(); }

  15. Exceptions Exceptions throws clause for checked exceptions /** Class to illustrate exception handling */ public class Ex { public static void main() { try { second(); } catch (OurException e) {} } public static void second() throws OurException { third(); } public static void third() throws OurException { throw new OurException("mine"); } } If you re interested in the controversy , http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

  16. Exceptions Demo 2: Pythagorean Solver Given a and b: solve for c in a2+ b2= c2 Reads in input from keyboard Handles any exceptions

  17. Key takeaways Thrown exceptions bubble up the call stack until they are handled by a try- catch block. In the system, the call of method main is in a try-catch statement, and its catch block prints out information about the thrown exception. http://xkcd.com/1188/ Alt-Text: I'm trying to build character but Eclipse is really confusing.

Related


More Related Content