An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Checked exception
Error
Runtime exception
Checked exceptions are checked at compile time. If a code throws a checked exception, then the associated block or method must handle the exception. For example,
FileNotFoundException
is a checked exception. If a method creates theFileInputStream
object to read data from, a file must handleFileNotFoundException
. If the specified file does not exist, thenFileNotFoundException
occurs and this exception must be caught or thrown.Errors are exceptional conditions that are external to the application and it's not possible to anticipate and recover from them, for example, hardware failure, stack overflow error, and out of memory error. These errors should not be handled.
Runtime exceptions are unchecked exceptions and these exceptions are not checked at compile time. Runtime exceptions can occur anywhere in a program, and throw
RuntimeException
when the user calls a method incorrectly. For example, in a method, if an argument is null, then a method might throwNullPointerException
, which is an unchecked exception.ArrayIndexOutOfBoundsException
is another example of a runtime exception. Errors and runtime exceptions are collectively known as unchecked exceptions.
Components of exception handler are try
, catch
, and finally
blocks, as shown in the figure that follows:
try { } catch (ExceptionType name) { } catch (ExceptionType name) { } finally { }
The first step in constructing an exception handler is to enclose the code that might throw an exception within a try
block. You associate exception handlers with a try
block by providing one or more catch
blocks directly after the try
block. No code can be between the end of the try
block and the beginning of the first catch
block.
Each catch
block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType
, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable
class. The handler can refer to the exception with name
. The catch
block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType
matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.
The finally
block always executes when the try
block exits. This ensures that the finally
block is executed even if an unexpected exception occurs. However, finally
is useful for more than just exception handling; it allows the programmer to avoid having cleanup code accidentally bypassed by a return
, continue
, or break
. Putting cleanup code in a finally
block is always a good practice, even when no exceptions are anticipated.
An example for exception handler components are as follows:
public class ExceptionHandlingExample { public static void main(String args[]){ try{ //code that might throw an exception in try block System.out.println("Try block executing..."); int i = 10/0; System.out.println(i); } catch(ArithmeticException e){ //handles ArithmeticException System.out.println("Arithmetic Exception catch block executing..."); System.out.println(e); } catch(NullPointerException e){ //handles NullPointerException System.out.println("Null Pointer Exception catch block executing..."); System.out.println(e); } finally{ System.out.println("finally block is always executed"); } } }
Try block executing... Arithmetic Exception catch block executing... java.lang.ArithmeticException: / by zero finally block is always executed
The throw
keyword is used to explicitly throw an exception. We can throw either checked or unchecked exceptions. The throw keyword is mainly used to throw a custom exception.
The following example performs division operation by passing two integer numbers as a parameter. If the denominator is zero, then throw ArithmeticException
; otherwise, calculate the division operation:
public class ThrowExample { private int calculateDivision(int number1, int number2){ if(number2 == 0){ //throw exception throw new ArithmeticException("Division not possible, denominator should be greater than zero."); } else{ //calculate division and return result return number1/number2; } } public static void main(String args[]){ try { ThrowExample obj = new ThrowExample(); //call calculateDivision method System.out.println(obj.calculateDivision(10, 0)); } catch (Exception e) { //if any exception catch and print the message System.out.println(e.getMessage()); } } }
The output will be as follows:
Division not possible, denominator should be greater than zero.
Note
Refer to the following reference to learn more about exception handling:
https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
Java IO is an API used for reading from a file and writing data to a file known as Java input and output operations. The File
class in the Java IO API gives access to the underlying filesystem. Using the File
class, you can perform the following operations:
Check if a file or directory exists
Create a directory if it does not exist
Read the length of a file
Rename or move a file
Delete a file
Check if the path is a file or directory
Read the list of files in a directory
The File
class gives access to the file and file system metadata. To perform read and write operations on a file, you should use FileInputStream
and FileOutputStream
. FileInputStream
and FileOutputStream
classes are used to read and write data in a file.
A FileOutputStream
class is an output stream for writing data to a File
or to a FileDescriptor
. Whether or not a file is available or may be created, depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream
(or other file-writing object) at a time. In such situations, the constructors in this class will fail if the file involved is already open. FileOutputStream
is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter
.
A FileInputStream
class obtains input bytes from a file in a filesystem. What files are available depends on the host environment. FileInputStream
is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader
.
The following example shows that FileOutputStream
writes the String contents as a stream of bytes into a file called contents.txt
. The FileInputStream
class makes it possible to read the contents of a file as a stream of bytes:
import java.io.FileInputStream; import java.io.FileOutputStream; public class FileIOStreamExample{ public static void main(String args[]){ try{ //FileOutputStream create file and connect write mode FileOutputStream fOut = new FileOutputStream("c:\\abc.txt"); String str = "Working with Java FileInputStream and FileOutputStream class"; //Contents of bytes and write to a file byte stringBytes[]=str.getBytes(); fOut.write(stringBytes); //Close the file fOut.close(); System.out.println("Written contents to file..."); //FileinputStraem connect read mode FileInputStream fIn = new FileInputStream("c:\\abc.txt"); int i; while((i = fIn.read())!= -1){ System.out.print((char)i); } //Close the file fIn.close(); System.out.println(); System.out.println("Read contents from file..."); }catch(Exception e){ System.out.println(e); } } }
The output will be as follows:
Written contents to file... Working with Java FileInputStream and FileOutputStream class Read contents from file...