Exceptions in Java
What are the Errors?
Errors are the wrong things or mistakes that can make a program wrong. A mistake might lead to an error to produce an unexpected result. An error may give you a wrong output or terminate the execution of the program. Therefore it is important to detect and manage properly all the possible error conditions in the program to get the correct result.
Type of Errors
- Compile time Errors
- Run time Errors
Compile Time Errors
All syntax errors will be detected and displayed by java compiler. So these errors are known as Compile Time Errors. Whenever the compiler displays an error it will not create the .class file.
Run Time Errors
Run Time Errors are errors that occur during the execution of the program. Sometimes a program may compile successfully creating .class file in Java but may not run properly. Such a program may give you bad result because of wrong logic or terminate due to errors. When such errors are encountered Java generates an error message and aborts the program.
Most common run-time errors are
- Dividing an integer by zero.
- Converting invalid String to a Number
- Try to store a value into an array of an incompatible class or type.
- Accessing an element that is out of the bound of the array.
- Passing a parameter that is not in a valid range.
Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program. When the Java interpreter encounters an error such as divide integer by zero, it creates an exception Object and throws it. We should catch that object and handle properly otherwise the interpreter will display an error message and terminate the program.
So this handling part is called as Exception Handling (Here we want the program to continue with the execution of the remaining code then we need try to catch the exception object thrown by the error condition and display an appropriate message for taking actions).
To taking actions to handle errors we need to do following tasks.
- Find the Problem (Hit the exception)
- Inform that an error has occurred (Throw the Exception)
- Receive the error information (Catch the Exception)
- Take proper actions (Handle it)
The error handling code basically consists of two parts, one to detect errors and throw the object other to catch exceptions and take appropriate actions.
Exceptions in Java can be categorized into two types.
- Checked Exceptions
Handles in the code itself using try-catch blocks.
- Unchecked Exceptions
JVM handles these exceptions. Not handled in the program code
Syntax
try{//Statement that causes on Exception
//Here exception Object creates and throws it to catch clause
}catch(ExceptionType e){//Statement that handles the exception
//Exception handler
}
Java uses keyword try to read a block of code that is likely to cause an error condition and throw an exception.
A catch block is added immediately after the try block and it uses for “catches” the exception “thrown” by the try block.
try{
}catch(ExceptionType e){
}
The try block can have one or more statements that could generate an exception and catch block can have one or more statements that are necessary to process the exception. If the catch parameter matches with the type of exception object, then the exception is caught and statements in the catch clause will be executed.
Otherwise, the exception is not caught and default exception handler will cause the execution to terminate.
Multiple Catch Statements
It is possible to have more than one catch statements in the catch block.
try{
}catch(ExceptionType e){
}catch(ExceptionType e){
}catch(ExceptionType e){
}
When an exception in a try block is generated, the java treats the multiple catch statements like cases in a switch statement
The first statement whose parameter matches with the exception object will be and the remaining statements will be skipped.
Exercise 1
Write a java program to input two numbers into an array and divide the first element by the second element.
package exceptiontutorial;import java.util.Scanner;/**
*
* @author Kasun Dissanayake
*/
public class ExceptionTutorial {public static void main(String[] args) {
int[] array = new int[2];
int result = 0;
Scanner scanner = new Scanner(System.in);
try {
array[0] = scanner.nextInt();
array[1] = scanner.nextInt();
result = array[0]/array[1];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Wrong index");
} catch (ArithmeticException e) {
System.out.println("Wrong division");
}
System.out.println("Result is : " + result);
}
}
Finally Statement
Finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block.
try {
} finally{
}-----------------------------------try {
}catch(){
}finally{
}
When finally block is defined this is guaranteed to execute regardless of whether or not an exception is thrown. Change the previous code using a finally block.
package exceptiontutorial;import java.util.Scanner;/**
*
* @author Kasun Dissanayake
*/
public class ExceptionTutorial {public static void main(String[] args) {
int[] array = new int[2];
int result = 0;
Scanner scanner = new Scanner(System.in);
try {
array[0] = scanner.nextInt();
array[1] = scanner.nextInt();
result = array[0]/array[1];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Wrong index");
} catch (ArithmeticException e) {
System.out.println("Wrong division");
}finally{
System.out.println("Result is : " + result);}
}
}
How to throw our own exceptions?
We can throw our exceptions by using the keyword throw as follows.
throw new Throwable subclass;
Example 2
Write a program to input two numbers and display the output of the division. If both numbers are zero display message as “Both Numbers are zero”
package exceptiontutorial;import java.util.Scanner;/**
*
* @author Kasun Dissanayake
*/
class MyClass extends Exception{public MyClass( String x) {
super(x);
}
}
public class ExceptionTutorial {public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int c ;
try {
if(a == 0 && b == 0){
throw new MyClass("Both Numbers are zero");
}
} catch (MyClass e) {
System.out.println(e.getMessage());
}
c = a / b;
System.out.println("Result: " +c);
}
}
There are some cases a method can throw a certain kind of exceptions but there is no exception handling mechanism to handle those exceptions within the method. In such cases, we can define exceptions with the method itself. Exceptions could be expected from the caller method and caller must be prepared with some catching mechanism to deal with it (Throws clause is used in such situations).
Example 3
Write a class which has a method call divide with two integer parameters and divide the first number by the second number. Handle Exception.
package exceptiontutorial;/**
*
* @author Kasun Dissanayake
*/
class MyClass {public void devide(int a, int b) throws ArithmeticException{
int c = a/b;
System.out.println("Answer : "+c);
}
}
public class ExceptionTutorial {public static void main(String[] args) {
MyClass myClass = new MyClass();
try {
myClass.devide(2, 3); // You can change para here
} catch (ArithmeticException e) {
System.out.println("Wrong division");
}
}
}
See you in the next tutorial.
Thank you!