how do you handle exceptions in java
I use try & catch blocks to handle any exceptions in my code.
I am familiar with major checked and unchecked exceptions and
handle it accordingly to make my code execution smooth
how do you handle exceptions in java
I use try & catch blocks to handle any exceptions in my code.
I am familiar with major checked and unchecked exceptions and
handle it accordingly to make my code execution smooth
can we have multiple catch block for a try block
In some cases our code may throw more than one exception.
In such case we can specify two or more catch clauses, each catch handling
different type of exception. When an exception is thrown jvm checks each
catch statement in order and the first one which matches the type of
exception is execution and remaining catch blocks are skipped.
Try with multiple catch blocks is highly recommended in java.
If try with multiple catch blocks are present the order of catch blocks is
very important and the order should be from child to parent.
Java Catching Exceptions
// A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2]; // Size 2
System.out.println("Access element three :" + a[3]); // Accessing 3rd element
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us