Exception Handling in Java: Try, Catch, and Throw
Introduction:
In Java, exception handling is one of the most important concepts that handles runtime errors and allows the program to continue executing. When creating Java projects, you will inevitably encounter errors such as runtime exceptions, I/O exceptions, class not found exceptions, etc. This allows developers to separate code that is prone to errors from other code, manage specific exceptions, and retain the program flow without having to end it.
Additionally, exception handling makes a program more reliable, easier to debug, and improves user experience with clearer error messages. It is, therefore, an important skill in writing robust and high-level Java applications. In this article, we’ll discuss a brief overview of exception handling in Java, like try-catch blocks, and the throw keyword in Java.
Exception handling in Java:
Exception handling is used to manage the runtime errors as the normal flow of the application can be maintained. Many global companies use the Java programming language because it creates large projects and also maintains the normal flow of the application.
Example:
public class A {
public static void main(String[] args) {
int a = 15;
int b = 0;
int res = a / b;
System.out.print("Show the result: " + res);
}
}
Output:
ERROR!
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example (Without Exception handling to solve this error)
Code:
public class A {
public static void main(String[] args) {
int a = 15;
int b = 0;
if (b != 0) {
int res = a / b;
System.out.println("Result: " + res);
} else {
System.out.println("Error: Cannot divide by zero.");
}
}
}
Output:
ERROR!
Error: Cannot divide by zero.
Types of Exception in Java
There are two types of exception hierarchy in Java that are shown below:
1) Checked Exception:
Checked exceptions are a part of exceptions checked at compile-time. These exceptions included such as ClassNotFoundException, IOException and SQLException, etc.
2) Unchecked Exception:
Unchecked exceptions an also part of the exception checked during the runtime. These exceptions are not checked at compile time. It includes such exceptions as ArithmeticException, NullPointerException and IndexOutOfBoundsException etc.
Try Block
This keyword handles the specified block, where it shows the error in the code. This cannot be use try block alone. After try-catch blocks, we write finally blocks.
Syntax:
try {
// Write your code here that throws an exception
}
Catch Block
This block handles the exception the declaration the type of the exception, given the number of parameters. It is written with the try block statement.
Syntax:
catch (Exception error) {
}
Syntax of the try-catch blocks:
try {
//Write your code here that throws an exception
} catch (Exception err) {
}
Example:
public class Main {
public static void main(String[] args) {
try {
int x = 50;
int y = 0;
int res = x/y;
System.out.print(res);
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("This line will be executed whether error occurs or not");
}
}
Output:
java.lang.ArithmeticException: / by zero
This line will be executed whether error occurs or not
Nested try Block
If multiple error occurs in your code, you can use nested try block. Because the try block used for that may throw an exception.
Syntax:
try {
// code throws an exception in outer block
try {
// code throw an exception in an inner block
} catch (Exception e) {
// Handle inner exception
}
// More code in outer try block
} catch (Exception e) {
// Handle outer exception
}
public class NestedTryExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner Catch block: Invalid array index!");
}
int a1 = 10;
int b1 = 0;
int result = a1/b1;
} catch (ArithmeticException e) {
System.out.println("Outer Catch block: Division by zero!");
}
}
}
Output:
Inner Catch block: Invalid array index!
Outer Catch block: Division by zero!
Nested Catch Block
Nested catch blocks are used to manage several types of exceptions. Each try block contains one or more catch blocks. One try block manages the many throws different types of exceptions.
Syntax:
try {
//code that may throw exception
}
catch(Exception e1) {
//handle exception code
}
catch(Exception e2) {
//handle exception code
}
catch(Exception e3) {
//handle exception code
}
catch (Exception e) {
//handle common exception
}
Example:
public class NestedCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer Catch Block: Array index out of bounds!");
try {
int num = Integer.parseInt("abc");
} catch (NumberFormatException e1) {
System.out.println("Inner Catch Block: Invalid number format!");
}
}
}
}
Output:
Outer Catch Block: Array index out of bounds!
Inner Catch Block: Invalid number format!
Throw Exception
Throw can be used for both checked and unchecked exceptions. This keyword is used for automatically throw an exception from the block of code. It controls the flow of the execution code.
Syntax:
throw new Exception ("Show error Message");
Example:
public class ThrowExample {
public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Age must be 18 or above.");
}
System.out.println("Eligible to vote.");
} catch (ArithmeticException e) {
System.out.println("Exception : " + e.getMessage());
}
}
}
Output:
Exception : Age must be 18 or above.
Conclusion:
In this article, we understand the “Exception Handling in Java: Try, Catch, and Throw”. It provides reliable and maintainable applications. With the use of exception handling, programmers handle runtime and compile-time errors and debug the program. Try block is used to throw an exception, catch manages the occurrence of an exception in your code, and throw allows for explicitly throwing an exception.
I suggest you learn Java programming from the Tpoint tech website, as it provides Java Tutorials, interview questions, and all its related topics in easy language.
Comments
Post a Comment