Monday, April 28, 2025

Java OO Tutorial - Try..Catch..Finally

In Java, try, catch, and finally are used together to handle exceptions or errors that occur during program execution.

The try block contains the code that may throw an exception. This block is followed by one or more catch blocks that catch the exception and handle it accordingly. If an exception is thrown in the try block, the catch block with a matching exception type will execute.

The finally block, which is optional, is used to execute code that needs to be executed regardless of whether an exception is thrown or not. This block is typically used to release any resources that were acquired in the try block, such as closing a file or releasing a database connection.

public class Main {	
	
	public static void main(String[] args) {
		
		String[] monitors = { "Dell", "IBM", "Benq" };
		
		try {
			System.out.println(monitors[2]);
		} 
		
		catch (Exception z) {
			System.out.println("Error 4731 - Can't find specific index");
			System.out.println(z);
		} 
		
		finally {
			System.out.println("--------------------------");
			System.out.println("I will run no matter what.");
			System.out.println("--------------------------");
		}						
	}		
}

Here's a line-by-line explanation of the code: 

public class Main {

This line declares a public class named Main

public static void main(String[] args) {

This line declares the main() method which is the entry point of the program. It takes an array of strings as a parameter. 

String[] monitors = { "Dell", "IBM", "Benq" };

This line declares an array of strings named monitors and initializes it with three elements: "Dell", "IBM", and "Benq"

try {
    System.out.println(monitors[2]);
}

This line starts a try block which contains the code that may throw an exception. It tries to print the value of the element at index 2 of the monitors array using the println() method. 

catch (Exception z) {
    System.out.println("Error 4731 - Can't find specific index");
    System.out.println(z);
}

This line starts a catch block which catches any Exception that is thrown in the try block. If an exception is caught, the block prints an error message and the exception message to the console. 

finally {
    System.out.println("--------------------------");
    System.out.println("I will run no matter what.");
    System.out.println("--------------------------");
}

This line starts a finally block which is executed whether or not an exception is thrown in the try block. This block prints a separator line and a message to the console.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...