Errors are unwanted issues that occur in a program that cannot be handled by a program. They may even result in a program crashing. Exceptions are issues that may occur when a program is running that can be foreseen. For example, if a user passes an incorrect file path in the arguments of a Java program.
There are two types of exceptions: checked and unchecked. Checked exceptions are exceptions that a programmer can handle and look out for by using try-catch blocks, and found when a program is compiling. Unchecked exceptions occur during runtime.
IOExceptions
are exceptions that are related to input and/or output in a program and can be classified as checked exceptions.
Some examples of when IOExceptions
occur include:
- Failed attempts at trying to access a file.
- The end of a file has been reached.
- The file a program is attempting to access cannot be found.
- An input/output operation has been interrupted.
We can code our program to handle IOExceptions
in areas of our code where we are dealing with input and output. To start off we must first import the IOExceptions
class into our program using import java.io.IOException.
Have a look at the block of code below to see how we have modified one of the examples from the previous exercises to use catch IOExceptions
.
There are many ways we may choose to handle an exception. We may choose to print an error using System.out.println()
or run a new instance of the program.
// Declare FileOutputSteam FileOutputStream output = new FileOutputStream("output.txt"); String statement = "Hello World!"; try { // Convert statement to bytes. byte[] statementBytes = statement.getBytes(); // Write all contents to file output.write(statementBytes); // Close file output.close(); } catch(IOException e) { // Handle exception System.out.println("There has been an IO exception"); System.out.println(e);
Instead of a try-catch block, we can also use the keyword throws
so that the exception is handled by the program itself.
public class Sample { public static void main(String[] args) throws IOException { … } }
Instructions
Run the code to see what happens!