QA's approach 2 Java - Exception Handling with examples
Exception Handling:
Exceptions arise from different kind of situations such as:
1. Invalid data entered by user & its not validated & allowed
2. Insufficient RAM/Disk space
3. Hardware failure
4. Network connection failure
5. Database server down etc.
Java being an object oriented programming language, whenever an error occurs while executing a statement, it creates an exception object and then the normal flow of the program halts and JVM tries to find the Handler that can handle the raised exception.
The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc.
When the exception occurs in a method, the process of creating the exception object and handing it over to runtime environment is called “throwing the exception”.
Once runtime receives the exception object, it tries to find the handler for the exception. Exception Handler is the block of code that can process the exception object. The logic to find the exception handler is simple – starting the search in the method where error occurred, if no appropriate handler found, then move to the caller method and so on. So if methods call stack is A->B->C and exception is raised in method C, then the search for appropriate handler will move from C->B->A. If appropriate exception handler is found, exception object is passed to the handler to process it. The handler is said to be “catching the exception”. If there are no appropriate exception handler found then program terminates printing information about the exception.
Exception Handling Keywords:
Once runtime receives the exception object, it tries to find the handler for the exception. Exception Handler is the block of code that can process the exception object. The logic to find the exception handler is simple – starting the search in the method where error occurred, if no appropriate handler found, then move to the caller method and so on. So if methods call stack is A->B->C and exception is raised in method C, then the search for appropriate handler will move from C->B->A. If appropriate exception handler is found, exception object is passed to the handler to process it. The handler is said to be “catching the exception”. If there are no appropriate exception handler found then program terminates printing information about the exception.
Exception Handling Keywords:
Example:
package exceptionHandling;
import java.io.IOException;
import java.util.Scanner;
public class Exception {
int age;
public int setAge() {
boolean flag = true;
Scanner sc = new Scanner(System.in);
while (flag) {
System.out.println("Please Register your age. To continue enter Y, else N");
String x = sc.next();
if (!((x.equalsIgnoreCase("Y")) || (x.equalsIgnoreCase("N")))) {
System.out.println("Invalid entry, Please try again");
continue;
} else if (!x.equalsIgnoreCase("Y")) {
System.out.println(
"Thanks for using the Registration app to enroll your age, you will be logged out immediately");
System.exit(0);
}
flag = false;
}
System.out.println("Please enter your age");
age = sc.nextInt();
System.out.println("Registered Voters age is:" + age + "yrs. "
+ "Do u wish to continue? If yes, please enter Y else N to make corrections");
if (sc.next().equalsIgnoreCase("Y")) {
} else {
setAge();
}
return age;
}
public static void main(String[] args) {
try {
exceptionTest((new Exception()).setAge());
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println("Please correct your age, if you are a eligible Voter");
String[] input = { "a" };
main(input);
}
}
static void exceptionTest(int age) throws IOException {
if (age < 18)
throw new IOException("User is not eligible for voting, Users age is: " + age+" under 18 years);
else
System.out.println("Thanks for Registering, Users age is: " + age + " and is eligible for voting");
}
}
2. throws – When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
3. try-catch – We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.
4. finally – finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.
Example with Custom Exception:
package exceptionHandling;
import java.io.IOException;
import java.util.Scanner;
public class Exception {
int age;
public int setAge() {
boolean flag = true;
Scanner sc = new Scanner(System.in);
while (flag) {
System.out.println("Please Register your age. To continue enter Y, else N");
String x = sc.next();
if (!((x.equalsIgnoreCase("Y")) || (x.equalsIgnoreCase("N")))) {
System.out.println("Invalid entry, Please try again");
continue;
} else if (!x.equalsIgnoreCase("Y")) {
System.out.println(
"Thanks for using the Registration app to enroll your age, you will be logged out immediately");
System.exit(0);
}
flag = false;
}
System.out.println("Please enter your age");
age = sc.nextInt();
System.out.println("Registered Voters age is:" + age + "yrs. "
+ "Do u wish to continue? If yes, please enter Y else N to make corrections");
if (sc.next().equalsIgnoreCase("Y")) {
} else {
setAge();
}
return age;
}
public static void main(String[] args) {
try {
exceptionTest((new Exception()).setAge());
} catch (UserException e) {
System.out.println(e.getMessage());
System.out.println("Please correct your age, if you are a eligible Voter");
String[] input = { "a" };
main(input);
}
}
// static void exceptionTest(int age) {
//try {
//
// if (age < 18)
// throw new UserException("User is not eligible for voting, Users age is: " + age);
// else
// System.out.println("Thanks for Registering, Users age is: " + age + " and is eligible for voting");
//
//} catch (UserException e) {
// System.out.println(e.getMessage());
// System.out.println("Please correct your age, if you are a eligible Voter");
//
//}
//the above statement doesnt contain the throws keyword, hence the exception is thrown within the exceptionTest method & should be handled in there itself as it is not propagated using throws -
In the case '// static void exceptionTest(int age) ' the Catch block defined in the uncommented program above will become unreachable as this Exception is never propagated, hence never reachable to the Catch block defined above. JVM throws an error message unreachable Catch block.
static void exceptionTest(int age) throws UserException {
//Since Exception is propagated, the Exception is Caught by Catch block defined in main method
if (age < 18)
throw new UserException("User is not eligible for voting, Users age is: " + age);
else
System.out.println("Thanks for Registering, Users age is: " + age + " and is eligible for voting");
}
}
Create Custom Exception Class 'UserException'
package exceptionHandling;
public class UserException extends Throwable
{
public UserException(String message) {
super(message);
}
}
package exceptionHandling;
import java.io.IOException;
import java.util.Scanner;
public class Exception {
int age;
public int setAge() {
boolean flag = true;
Scanner sc = new Scanner(System.in);
while (flag) {
System.out.println("Please Register your age. To continue enter Y, else N");
String x = sc.next();
if (!((x.equalsIgnoreCase("Y")) || (x.equalsIgnoreCase("N")))) {
System.out.println("Invalid entry, Please try again");
continue;
} else if (!x.equalsIgnoreCase("Y")) {
System.out.println(
"Thanks for using the Registration app to enroll your age, you will be logged out immediately");
System.exit(0);
}
flag = false;
}
System.out.println("Please enter your age");
age = sc.nextInt();
System.out.println("Registered Voters age is:" + age + "yrs. "
+ "Do u wish to continue? If yes, please enter Y else N to make corrections");
if (sc.next().equalsIgnoreCase("Y")) {
} else {
setAge();
}
return age;
}
public static void main(String[] args) {
try {
exceptionTest((new Exception()).setAge());
} catch (UserException e) {
System.out.println(e.getMessage());
System.out.println("Please correct your age, if you are a eligible Voter");
String[] input = { "a" };
main(input);
}
}
// static void exceptionTest(int age) {
//try {
//
// if (age < 18)
// throw new UserException("User is not eligible for voting, Users age is: " + age);
// else
// System.out.println("Thanks for Registering, Users age is: " + age + " and is eligible for voting");
//
//} catch (UserException e) {
// System.out.println(e.getMessage());
// System.out.println("Please correct your age, if you are a eligible Voter");
//
//}
In the case '// static void exceptionTest(int age) ' the Catch block defined in the uncommented program above will become unreachable as this Exception is never propagated, hence never reachable to the Catch block defined above. JVM throws an error message unreachable Catch block.
static void exceptionTest(int age) throws UserException {
//Since Exception is propagated, the Exception is Caught by Catch block defined in main method
if (age < 18)
throw new UserException("User is not eligible for voting, Users age is: " + age);
else
System.out.println("Thanks for Registering, Users age is: " + age + " and is eligible for voting");
}
}
Create Custom Exception Class 'UserException'
package exceptionHandling;
public class UserException extends Throwable
{
public UserException(String message) {
super(message);
}
}
Comments
Post a Comment