Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to handle exceptions?
3.
try block
3.1.
Nested try block
4.
catch block
4.1.
Multi-Catch block
5.
throw block
6.
throws block
7.
Frequently Asked Questions
7.1.
Is catch block mandatory in Java?
7.2.
Why is finally block needed?
7.3.
How many exceptions are there in Java?
8.
Conclusion
Last Updated: Mar 27, 2024

Try, catch, throw and throws in Java

Introduction

When it comes to programming, we are concerned about errors. Whenever you write the code in Java or in any other programming language, the first concern you have is encountering errors. For example, you will get errors when you want to declare a variable but forget to do so and then try to use it.

Must Read, Multithreading in javaDuck Number in Java

How to handle exceptions?

So if we talk about Handling Exceptions , we have two things here. We have errors and exceptions. So basically, when you write a program, there might be many different kinds of exceptions. 

For example, 

  • You are trying to open a file, and the file doesn't exist, so there is an exception.
  • You are asking for the user's input, and the user is not giving you the input, so that's an exception. 
  • You are trying to run a process, but the CPU is unavailable, so that's an exception.
  • You are trying to divide a number by zero, which is also an exception.
     

So there are different kinds of exceptions if you talk about the exception hierarchy.

We utilize the throw keyword to throw an exception from the code explicitly. Any method or static block can be used. This exception must be a Throwable subclass. It can also be a Throwable in and of itself. We can not throw multiple exceptions with a single throw.

The keyword throws can be used in the method declaration. It specifies the exceptions that this procedure can throw.

Normally, whenever you have an "able" at the end, such as cloneable, closeable, or serializable. All these are "able" interfaces, but this throwable is not an interface; it's a class. And the subclass of throwable is an exception. We must use try-catch to handle these exceptions.

In Java, there are two types of exceptions. They are: 

  1. Checked exceptions 
  2. Unchecked exceptions 

 

Checked exceptions 

Checked exceptions are exceptions other than Runtime Exceptions that the compiler examines during compilation to verify if the programmer has handled them. Compilation errors will occur if these exceptions are not handled/declared in the application—for example, IOException, SQLException, ClassNotFoundException, etc.

 

Unchecked Exceptions 

Unchecked Exceptions are another name for Runtime Exceptions. These exceptions are not verified at compilation time; thus, the compiler has no way of knowing whether the programmer has dealt with them or not. The programmer's job is to deal with these exceptions and offer a safe exit. For example, NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException etc.
 

Example of Basic Exception:

class Exception {
	public static void main(String args[]) {
		try {
			//code that may raise exception
		} catch (Exception e) {
			// rest of the program
		}
	}
}

 

Some of the examples of Java Exception 

An exception can occur if it encounters the following issues:

i. Invalid input

ii. Accessing the elements of an array beyond its range

iii. Divide by zero errors

iv. Hard disk crash

v. Heap memory exhausted

vi. Opening a non-existent file

 

Advantages of Exception Handling

  • Error-handling code is separated from typical business logic code.
  • Errors are propagating up the call stack.
  • Error kinds are grouped and differentiated.
     

How to handle exceptions in Java?

As I previously stated, properly managing exceptions is critical, and if we don't handle them, the system will fail. But how do you deal with these exceptions?

To handle Exceptions, Java provides several methods, such as:

  • try
  • catch
  • finally
  • Throw
  • throws

try block

The try block is a domain that has a list of statements in which exceptions may occur. Try block cannot be used alone; therefore, it is always accompanied by either catch block, finally block, or both.
 

Syntax:

try{
	//code that may throw an exception
} catch(Exception_class_Name ref){
	//rest of the code
}

Nested try block

As the name implies, a nested try block is a try block inside a try block.
 

Example:

public class Main {
	// main function
	public static void main(String args[]) {
		try {
			try {
				// we try to divide a number by 0.
				// this will create an Arithmetic Exception
				int x = 5 / 0;
			}
			// this catch block will handle 
			// Arithmetic Exception
			catch (ArithmeticException e)
			{
				System.out.println("Arithmetic xception handled in this catch block");
			}
			try {
				int arr[] = { 5, 0 };
				System.out.println(arr[3]);
			}
			// this catch block will handle
			// Array Index Out of Bounds Exeception
			catch (ArrayIndexOutOfBoundsException e)
			{
				System.out.println("Array Index Out of Bounds Exception is handled in this catch block");
			}
		} catch (Exception exception) {
			System.out.println("remaining code");
		}
	}
}

 

Output:

Try it on online java compiler

catch block

The catch block is a method that is utilized to grasp exceptional cases. It always accompanies try block. Finally block can accompany a catch block after it accompanies a try block. A number of catch blocks can be linked with a try block. It can handle many exception cases in all linked blocks. The particular catch block assigned the code with exception handles the exception.

try {
	//statements that may give an exception
} catch (exception(type) e(object)) {
	//error handling code
}

Multi-Catch block

If you need to perform multiple tasks in response to multiple exceptions, you can use the multi-catch block.

Example:

import java.util.*;
public class Main {
	// main function
	public static void main(String args[]) {
		ArrayList<String> al = new ArrayList<String> ();
		al.add("Coding");
		al.add("Ninjas");
		try {
			String wrongAccess = al.get(5);
		} catch (ArithmeticException ae) {
			System.out.println("Wrong arithmetic expression. Please try again!");
		} catch (IndexOutOfBoundsException indxExcep) {
			System.out.println("You tried to access wrong index. Please check and try again!");
		} catch (Exception e) {
			System.out.println("This will handle any exception!");
		}
	}
}


Output:


Also see,  Swap Function in Java

throw block

In Exception Handling, the throw keyword explicitly throws an exception from a method or constructor. We can throw either checked or unchecked exceptions in Java by throw keyword. The "throw" keyword is mainly used to throw a custom exception. The only object of the throwable class or its subclasses can be thrown. When a throw statement is encountered, program execution is halted, and the nearest catch statement is searched for a matching kind of exception.
 

Example:

public class ThrowExample {
	static void checkEligibilty(int stuage, int stuweight) {
		// check if the student's age is less than 15
		// and the student's weight is greater than 45
		if (stuage<15 && stuweight<45) {
			throw new ArithmeticException("Student is not eligible for registration");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}
	public static void main(String args[]) {
		System.out.println("Welcome to the Registration process!!");
		checkEligibilty(10, 39);
		System.out.println("Have a nice day..");
	}
}


Output:

throws block

Any method that might cause exceptions must identify all of the exceptions that can occur during its execution. The programmer calling the method is aware of which exceptions must be handled. The throws keyword can be used to do this.

 

Example:

import java.io.*;
class ThrowExample {
	void myMethod(int num) throws IOException, ClassNotFoundException {
		if (num == 1)
			throw new IOException("IOException Occurred");
		else
			throw new ClassNotFoundException("ClassNotFoundException");
	}
}
public class Main {
	public static void main(String args[]) {
		try {
			ThrowExample obj = new ThrowExample();
			obj.myMethod(1);
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
}


Output:

 

Must Read Static Blocks In Java. Fibonacci Series in Java and Hashcode Method in Java

Frequently Asked Questions

Is catch block mandatory in Java?

No, not at all. Unless and until a finally block follows the try block, it is unnecessary to put catch after the try block. Keep in mind that after a try, a catch, a finally, or both can be useful.
 

Why is finally block needed?

In Java, the finally block is used to place critical code such as cleanup code, closing a file, or closing a connection. The finally block checks whether an exception has been raised and whether it has been handled. Regardless of whether the exception happens, a fina block contains all the crucial statements.
 

How many exceptions are there in Java?

There are three types of exceptions:
1. The checked exception. 
2. The error. 
3. The runtime exception.

Conclusion

This blog has discussed exception handling methods like try, catch, throw, and throws in Java with examples. Along with a few more important terminologies with its code.

Recommended Topic: Difference Between Data Analyst and Business Analyst

We hope that this blog has helped you enhance your knowledge regarding try, catch, throw and throws in Java and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass