A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself or pass it on. Either way, at some point, the exception is caught and processed.
The programs you write can generate many types of potential exceptions, such as when you do the following:
In Java there are three types of loops:
These errors are called exceptions because, presumably, they are not usual occurrences; they are “exceptional.” The object-oriented techniques to manage such errors comprise the group of methods known as exception handling.
Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. Let’s take an example program which will do take two numbers from user and print division result on screen. This might lead to exception condition if the denominator is zero.
Java Code: Go to the editor
import java.util.Scanner;
public class DivideExceptionDemo {
public static void main(String[] args) {
//Scanner class is wrapper class of System.in object
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter first number(numerator): ");
int numerator = inputDevice.nextInt();
System.out.print("Please enter second number(denominator): ");
int denominator = inputDevice.nextInt();
new DivideExceptionDemo().doDivide(numerator, denominator);
}
public void doDivide(int a, int b){
float result = a/b;
System.out.println("Division result of "+ a +"/"+b +"= " +result);
}
}
Output:
Outputs based on user input combinations:
Handling Exceptions:
There are two ways of handling the exception, first catch the exception and take corrective action or throws the exception to the calling method which will force the calling method to handle it.
Java Code: Go to the editor
import java.util.Scanner;
public class DivideExceptionHandle {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter first number(numerator): ");
int numerator = inputDevice.nextInt();
System.out.print("Please enter second number(denominator): ");
int denominator = inputDevice.nextInt();
new DivideExceptionHandle().doDivide(numerator, denominator);
}
public void doDivide(int a, int b){
try{
float result = a/b;
System.out.println("Division result of "+ a +"/"+b +"= " +result);
}catch(ArithmeticException e){
System.out.println("Exception Condition Program is ending ");
}
}
}
Output:
Outputs based on user input combination:
Java Code: Go to the editor
import java.util.Scanner;
public class DivideExceptionThrows {
public static void main(String[] args){
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter first number(numerator): ");
int numerator = inputDevice.nextInt();
System.out.print("Please enter second number(denominator): ");
int denominator = inputDevice.nextInt();
try {
new DivideExceptionThrows().doDivide(numerator, denominator);
} catch (Exception e) {
System.out.println("Exception Condition Program is ending ");
}
}
public void doDivide(int a, int b) throws Exception{
float result = a/b;
System.out.println("Division result of "+ a +"/"+b +"= " +result);
}
}
As you can see either we can surround the code with try-catch block or we can re-throw it to be handled by calling the method. In this case, we are calling a method from the main() method so if we re-throw the exception it would be handled by JVM. Let us update the code and see output based on input combination
Output:
Outputs based on user input combination:
Nested Try-catch block:
The try statement can be nested. That is, a try statement can be inside the block of another try.Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.If no catch statement matches, then the Java runtime system will handle the exception. Below is the syntax of nested try-catch block.
Java Code: Go to the editor
public class NestedTryblockDemo {
public static void main(String[] args) {
try{
//some code which can throw Exception
try {
//Some code which can throw Arithmatic exception
try {
//Some code which can throw number format exception
}catch(NumberFormatException n){
//Number format Exception handling
}
}catch(ArithmeticException a){
//ArithmeticException Handling
}
}catch(Exception e ){
//General Exception(SuperClass of all Exception) Handling
}
}
}
Use of finally block:
When you have actions you must perform at the end of a try...catch sequence, you can use a finally block. The code within a finally block executes regardless of whether the preceding try block identifies an Exception. Usually, you use a finally block to perform cleanup tasks that must happen whether or not any Exceptions occurred, and whether or not any Exceptions that occurred were caught. In an application where database connection, files are being operated, we need to take of closing those resources in exceptional condition as well as normal condition.
Java Code: Go to the editor
public class TryCatchFinally {
public void Demo() {
try {
// statements to try
} catch (Exception e) {
// actions that occur if exception was thrown
} finally {
// actions that occur whether catch block executed or not
}
}
}
Summary:
We have learned about how exceptions are generated and various ways of handling exceptions. Catching exception or propagating exceptions. We have learned keywords like try, catch, finally, throws and programmatic use of these keywords.
Java Code Editor:
Previous: Java Branching Statements
Next:Checked and unchecked
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4