Java try…catch
What are try…catch Statements?
In the Article, we will Discuss about the try…catch Statements of java.
A try-catch block is a programming construct used to handle errors or exceptions that may occur during the execution of a program. The try block contains the code that may cause an exception to be thrown, while the catch block contains code that handles the exception if it occurs.
Java Try…catch Statements:
In Java, try and catch statements are used for handling exceptions that may occur during the execution of a program. The try block contains the code that might throw an exception, while the catch block contains the code that handles the exception if it occurs.
Initializing a try…catch block in Java:
Syntax:
try{ // Block of code Catch{ // Block of code }
Explanation:
- Try Block : Try block executes all the code and if exist, It passes the exception to the catch block.
- Catch Block : It is used to handle the Exception by declaring the type of exception within the parameter.
Java Program to Implement Try…Catch Statements:
import java.util.*; public class Main{ public static void main(String[] args) { // Try block Statements try { // Initializing an array int[] numbers = {1, 2, 3}; // This will throw an ArrayIndexOutOfBoundsException int result = numbers[3]; System.out.println("Result: " + result); } // Catch block Statements catch (ArrayIndexOutOfBoundsException e){ // Printing the Exception System.out.println("Exception caught: " + e); } } }
Output:
Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Explanation:
In the above program, the code in the try block attempts to access the element at index 3 of an array that only contains three elements. This would normally result in an ArrayIndexOutOfBoundsException being thrown. However, since the code is wrapped in a try-catch block, the catch block is executed instead, and a message is printed to the console.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment