How to Declare Exception Errors in Java
Errors can occur from several sources when the computer utilizes applications. These sources are either a programming error or errors that arise from mistakes made by the computer user. As the user, you would want the application to inform you as to what the specific error is rather than allow itself to to run with the error continuing to plague the system. The exception class was developed in Java to transfer control of the program application to a predetermined block of programming code to give the developer the opportunity to create predefined actions to take in the event of an error. For the Java programmer, creating a Java exception is a common action.
Instructions
-
-
1
Run the text editor in your computer. Save the files under the title "TestFile.java" by clicking on "File" and the "Save As" button to your computer's C: drive.
-
2
Input this code:
Public static void main (String[] args)
{
InputStream myInputStream;
File myFile;}
into the TestFile.java file. This creates a development environment to declare a Java exception:
-
-
3
Initiate the exception handling code with the usage of what is referred to as a "Try" block. An exception being thrown in the Java program may be a result of the "Try" block. A "File Not Found" exception occurs, when in this situation the Try block will load an input file that is not available.
Public static void main (String[] args)
{
InputStream myInputStream;
File myFile;
try
{
myFile = new Files(args[0]);
myInputStream = new InputStream(myFile);
}
} -
4
Add the exception handling code to the accompanying Try block of code to signify to the user that a "File Was Not Found" when the FileNotFound Exception is thrown:
Public static void main (String[] args)
{
InputStream myInputStream;
File myFile;
try
{
myFile = new Files(args[0]);
myInputStream = new InputStream(myFile);
}
catch (FileNotFoundException myException) {
System.out.println("myFile " + args[0] + " not found");
}}
-
1