Concept
What is a checked exception in Java?
ComputerScienceOne / Checked Exceptions
"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)."
Related Ideas
- How can a Scanner read input from a file?ComputerScienceOne · File Input
- How do you catch and handle an exception in Java?ComputerScienceOne · Catching Exceptions
- How can Java handle different exception types with multiple catch blocks?ComputerScienceOne · Catching Exceptions
- How do you create a custom exception in Java?ComputerScienceOne · Throwing Exceptions
- Why should the most specific exception types be caught before general ones?ComputerScienceOne · Throwing Exceptions
- What types of errors can occur when processing files?ComputerScienceOne · Error Handling
- How can you manually throw an exception in Java?ComputerScienceOne · Creating Custom Exceptions
- How do you create a custom exception in Java?ComputerScienceOne · Creating Custom Exceptions