03 Basic Exception and File Handling
03 Basic Exception and File Handling
Handling
Object Oriented Programming
Overview
Basic Exception Handling
• Exceptions and Exception Classes
• Exception vs. Error
• Exception Class Hierarchy
• Handle exceptions using a simple try-catch-finally block
• Exception handling constructs (try, catch, finally)
Basic Exception Handling
• Reader and Writer classes
• Reading and writing from/to a text file
Exception
• An exception is an event that interrupts the normal processing flow
of a program. This event is usually some error of some sort. This
causes our program to terminate abnormally.
• Some Exceptions classes:
ArrayIndexOutOfBoundsException
NumberFormatException
ArithmeticException
InputMismatchException
NegativeArraySizeException
StringIndexOutOfBoundsException
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException – array index is either less than 0 or
greater than or equal to the length of the array.
Example:
1. public class TryExceptions{
2. public static void main(String[] args){
3. String[] colors = {"red", "blue", "yellow"};
4. for(int i = 0; i <= colors.length; i++)
5. System.out.println(colors[i]);
6. }
7. }
NumberFormatException
NumberFormatException – use of an illegal number format.
Example:
1. public class TryExceptions{
2. public static void main(String[] args){
3. String number = "alpha";
4. int x = Integer.parseInt(number);
5. }
6. }
ArithmeticException
ArithmeticException – arithmetic errors such as division by zero.
Example:
1. public class TryExceptions{
2. public static void main(String[] args){
3. System.out.println(123 / 0);
4. }
5. }
InputMismatchException
InputMismatchException – input retrieved does not match the pattern for
the expected type, or the token is out of range for the expected type.
Example:
1. import java.util.Scanner;
2. public class TryExceptions{
3. public static void main(String[] args){
4. Scanner input = new Scanner(System.in);
5. int number = input.nextInt();
6. //input a non-integer value
7. }
8. }
NegativeArraySizeException
NegativeArraySizeException – created array with negative size.
Example:
1. public class TryExceptions{
2. public static void main(String[] args){
3. String colors[] = new String[-27];
4. }
5. }
StringIndexOutOfBoundsException
StringIndexOutOfBoundsException – a string index is either less than 0 or
greater than equal to the length of the string.
Example:
1. public class TryExceptions{
2. public static void main(String[] args){
3. String xmas = "Christmas";
4. for(int i = 0; i <= xmas.length(); i++)
5. System.out.println(xmas.charAt(i));
6. }
7. }
Errors vs. Exceptions
Errors Exceptions
Errors in java are of type java.lang.Error Exceptions in java are of type
java.lang.Exception
Errors happen at run time. They will not be Checked exceptions are known to compiler
known to compiler. where as unchecked exceptions are not
known to compiler because they occur at run
time.
It is impossible to recover from errors. You can recover from exceptions by handling
them through try-catch blocks.
Errors are mostly caused by the Exceptions are mainly caused by the
environment in which application is running. application itself.
Exception Class Hierarchy
IllegalThreadStateException
IllegalArgumentException
NumberFormatException
Exception
ArithmeticException
ArrayIndexOutOfBoundsException
RuntimeException IndexOutOfBoundsException
StringIndexOutOfBoundsException
NegativeArraySizeException
NoSuchElementException* InputMismatchException*
Handling Exceptions
1. try{
2. //write the statements that can generate an exception in this block
3. }
4. catch( <exceptionType> <varName> ){
5. //action that the program will do if an exception of a certain type occurs
6. }
7. . . .
8. catch( <exceptionType1> <varName1> ){
9. //action that the program will do if an exception of a certain type occurs
10. }
11. finally{
12. //add more cleanup code here
13. }
Handling Exceptions
Exceptions thrown during execution of the try block can be caught and handled
in a catch block. The code in the finally block is always executed. The following
are the key aspects about the syntax of the try-catch-finally construct:
• The try block notation is mandatory.
• For each try block, there can be one or more catch blocks, but only one finally
block.
• The catch blocks and finally blocks must always appear in conjunction with
the try block, and in the above order.
• A try block must be followed by at least one catch block OR one finally block,
or both.
• Each catch block defines an exception handle. The header of the catch block
takes exactly one argument, which is the exception its block is willing to
handle.
Handling Exceptions
1. public class TryExceptions{
2. public static void main(String[] args){
3. Scanner input = new Scanner(System.in);
4. try{
5. int number = input.nextInt();
6. int x = 45/number;
7. }catch(ArithmeticException t){
8. System.out.println("Cannot divide by 0");
9. }catch(InputMismatchException t){
10. System.out.println("Invalid input");
11. }finally{
12. System.out.println("Okay");
13. }
14. }
15. }
Handling Exceptions