Java Exceptions
Exception is unwanted condition which are occurred during the program execution. That is very dangerous, because they are produced unreliable situation which is produces unwanted result or terminate program execution abnormally. In Java programming is provide a mechanism to control exceptions errors in run time, That is called Exception Handling.
There are various type of situation possible which can producing an exception in our program. For example. Fail the resources of system, Reading a file which are not exist in particular location, Getting invalid input at program execution, Converting a value to unreliable other format, and so on.
Java Programming is provide two class which are handle error and throws exceptions. The name of this class are Error and Exception.
Error handling by try throw catch
There are four useful error handling statement are available in Java programming which can handle user custom code exception.
try {
// Write code which can producing exception
} catch(ExceptionType e1){
// Catch exception
} catch(ExceptionType e2){
// Catch exception
} catch(ExceptionType e3){
// Catch exception
} catch(ExceptionType e4){
// Catch exception
}
finally{
//This is Optionally
//That is used to clean up resources
}
try : This block are used to define statement which can be produce an exception.
throw : That is used to throw custom exception. In special case, when try statements are not generate any exception. But when programer are need to generate an custom exception to particular condition. In this situation throw statement can be reliable to implement custom exception.
catch : This block are working when try block statement are generated an exception of during program execution. There is possible you'll can use multiple catch block to single try block. Catch block are automatic execute when relative exception is occured.
finally: This is an resource free block. it are always work when error are occurred or not and they are optional block.
Let's see a condition which are producing an exception. For example suppose you are create an app which are dividing of two number which is given by user. In this scenario there is two situation are possible which can produce an exception. First is invalid input which are given by user and second is invalid operation. Invalid input means given value is not a form of an valid integers. And invalid operation means number is divide by zero. If you'll are solve this problem there are need to checking two test cases individually. let see this basic example
//Check both input are valid integers or not
if(divisor and dividend){
//When valid integer inputs
if(divisor!=0){
//When Valid divisor then do divide two numbers
}else{
//invalid divisor
}
}else{
//divisor invalid or dividend
}
In this code snippet there are default to check given input value is form of an integer because when assign string value to integer variable. Then program is terminating abnormally because that is invalid operation. So most of cases conditional statement are not suitable to check exception, especially when for user are inputting variable values and perform type conversion operation. let try to solve this problem by using exception handling.
import java.util.*;
public class ExceptionExample
{
public static void main(String[] args){
//make object of scanner class
Scanner action=new Scanner(System.in);
int divisor,dividend;
try{
System.out.print("Enter Two Numbers : ");
//input values
dividend=action.nextInt();
divisor=action.nextInt();
//divide operation
int result = dividend/divisor;
System.out.println("Result : "+ result);
}
catch(ArithmeticException e1){
System.out.println("Arithmetic Exception Occurred");
}
catch(java.util.InputMismatchException e2){
System.out.println("Invalid Input Value");
}
catch(Exception e3){
//When other exception is occured
System.out.println("Exception : "+e3);
}
finally{
//optionally when need to Reset value
divisor=0;
dividend=0;
}
}
}
Test cases
//First Test Case
Enter Two Numbers : One
Invalid Input Value
//Second Test Case
Enter Two Numbers : 46
4f
Invalid Input Value
//Third Test Case
Enter Two Numbers : 90
0
Arithmetic Exception Occurred
//Fourth case
Enter Two Numbers : 90
9
Result : 10
Ultimate goal of exception handling catching unwanted exception which are generating program execution. Exception handling are used to avoid multiple test condition (if-else statement) and increase readability of code. Inside catch block we can display custom user message or also use exception class inbuilt message. e.getMessage() are used to display inbuilt message of Exception class.
public class ExceptionExample{
public static void main(String[] args){
int divisor=0,dividend=90;
try{ //divide operation
int result = dividend/divisor;
System.out.println("Result : "+ result);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
/ by zero
Throw custom exception
throw statement are used to throw explicitly custom exception. There are following syntax.
throw Instance
Instance are create by new operator and exception class name. But this instance should be Throwable or subclass of Throwable. When throw statement are found then other next instruction execution of try block will stops. For example.
class ThrowException{
public static void main(String[] args){
int discount = 103;
try{
if(discount<0){
//Throw ArithmeticException custom exception
throw new ArithmeticException("Discount Are Less Than Zero");
}
else if(discount>100) {
throw new Exception("Discount Is More Than 100%");
}
System.out.println(" Given Discount is : "+discount );
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Discount Is More Than 100%
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment