Exception Handling Try Catch Answer

The program takes two integer inputs from the user and performs division. However, during this process, exceptions such as division by zero (ArithmeticException) or inputting non-integer values (InputMismatchException) may occur. These exceptions need to be handled to prevent the program from crashing.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Exception Handling Try Catch Answer HackerRank solution using CodeRankGPT:

The solution uses a try-catch-finally block to handle potential exceptions. In the try block, it attempts to perform the division. If an ArithmeticException (division by zero) occurs, it is caught and the exception is printed. If an InputMismatchException (non-integer input) occurs, it is also caught and the name of the exception class is printed. The finally block ensures that the Scanner object is closed regardless of whether an exception occurs or not.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.exceptionhandling;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 *
 */
public class JavaExceptionHandlingTryCatch {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		try {
			int x = sc.nextInt();
			int y = sc.nextInt();
			int z = x / y;
			System.out.println(z);
		} catch (ArithmeticException e) {
			System.out.println(e);
		} catch (InputMismatchException e) {
			System.out.println(e.getClass().getName());
		} finally {
			sc.close();
		}
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform