Bifalgorithm post · Computer science one · Checked Exceptions

What is a checked exception in Java?

What is a checked exception in Java? (Computer science one · Checked Exceptions) — "A checked exception in Java is an exception that must be explicitly caught…

Ideas in this flowchart

  • Checked exception in Java
  • A checked exception must be explicitly caught and handled.
  • Examples include Exception, IOException, and SQLException.
  • When a checked exception is thrown within a block of code, it requires explicit handling.
  • The exception must either be caught in the block or declared by the method.
  • One option is to catch and handle the exception inside the method.
  • The processFile() method can use a try-catch block for FileNotFoundException.
  • Another option is to declare that the method explicitly throws the exception.
  • A processFile() method that creates a Scanner without handling FileNotFoundException does not compile.
  • Declaring the exception forces callers of processFile() to catch it or throw it onward.
Feed/

What is a checked exception in Java?

No cover

Channel

Computer science one

1 page

"A checked exception in Java is an exception that must be explicitly caught and handled. For example, the generic Exception class is a checked exception (others include IOException, SQLException, etc.). If a checked exception is thrown within a block of code then it must either be caught and handled within that block of code or the method must be specified to explicitly throw the exception.\n\nFor example, the method\n\npublic static void processFile() {\n\nScanner s = new Scanner(new File(\"data.csv\"));\n\n}\n\nwould not actually compile because Scanner throws a checked FileNotFoundException. Either we would have to explicitly catch the exception:\n\npublic static void processFile() {\n\nScanner s = null;\n\ntry {\n\ns = new Scanner(new File(\"data.csv\"));\n\n} catch (FileNotFoundException e) {\n\n//handle the exception here\n\n}\n\n}\n\nor we would need to specify that the method processFile() explicitly throws the exception:\n\npublic static void processFile() throws FileNotFoundException {\n\nScanner s = new Scanner(new File(\"data.csv\"));\n\n}\n\nDoing this, however, would force any code that called the processFile() method to surround it in a try-catch block and explicitly handle it (or once again, throw it back to the calling method)."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.