Java and any other programing language will let you know whether you made a mistake or an error. When your code has an error, Java will complain by sending you an Error message. For instance, we forgot writing throws IOException in line 4 in the following example:
1. import java.util.Scanner;
2. import java.io.*;
3. public class ExceptionHandlingExample01{
4. public static void main(String [] args)/*here*/{
5. Scanner input = new Scanner(new File("niceday.txt"));
6. }
7. }
After running this program, we will get the following result:
Error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
A cheap solution for this problem (but not convenient as discussed in next section) is just throwing that exception by replacing the bold phrase above in line four like this:
4. public static void main(String [] args)throws IOException{. . .}
Before going to another case, let's explore what is saved on the user desktop in the image below. The userDesktop contains two folders COSC1436 and COSC1437; we can also observe that niceDay.txt file is saved below this folder. Next, let's again run ExceptionHandlingExample01; at this point, you might observe this new message from the terminal:
Exception in thread "main" java.io.FileNotFoundException: niceday.txt(No such file or directory)
After receiving this message, we are able to learn two things. The first one is that this is not a syntax error; instead, it is an Exception. The second thing, we need to recognize this exception occurred because ExceptionHandlingExample01.java and niceDay.txt are not saved in the same directory. In other words, niceDay.txt and ExceptionHandlingExample01.java must be saved inside the COSC1437 folder to prevent this exception message. In short, Syntax Errors and Exceptions are treated differently in Java, so our main task is to provide the appropriate throw when needed or save all needed files in the same directory.
AP CS A
[Exception Handling]
AL-14. Investigate security vulnerabilities in various data structures.
CYB-17. Implement programs that properly handle exceptions and error conditions.
ACM CCECC
[Exception Handling]
SDF-12. Investigate common coding errors that introduce security vulnerabilities
CS2
[Exception Handling]
130.422.c.4.n Identify and debug compile, syntax, runtime, and logic errors.
Dealing with runtime errors in programs (exception handling)
Basic concept of programming errors, testing, and debugging
Read and understand the code and identify errors in it.