Do the Try Again After Catching Exception Java
- Get link
- Other Apps
What is Exception in Coffee?
Exception in Java is an result that interrupts the execution of programme instructions and disturbs the normal catamenia of program execution. It is an object that wraps an error event information that occurred inside a method and it is passed to the runtime system. In Java, exceptions are mainly used for indicating different types of error conditions.
In this tutorial, you will acquire-
- What is Exception?
- Why do nosotros demand Exception?
- How to Handle Exception
- Endeavor Take hold of Cake
- Coffee Exception class Hierarchy
- Java Finally Block
There are two types of errors:
- Compile fourth dimension errors
- Runtime errors
Compile time errors can be again classified again into two types:
- Syntax Errors
- Semantic Errors
Syntax Errors Example:
Instead of declaring int a;
y'all mistakenly declared it every bit in a;
for which compiler will throw an error.
Example: You have declared a variable int a;
and after some lines of code you once more declare an integer as int a;
. All these errors are highlighted when you compile the lawmaking.
Runtime Errors Example
A Runtime error is called an Exceptions error. Information technology is any event that interrupts the normal period of plan execution.
Instance for exceptions are, arithmetic exception, Nullpointer exception, Divide by aught exception, etc.
Exceptions in Java are something that is out of developers control.
Click here if the video is not accessible
Why exercise we demand Exception?
Suppose you accept coded a program to access the server. Things worked fine while you were developing the lawmaking.
During the actual product run, the server is downward. When your plan tried to access it, an exception is raised.
How to Handle Exception
So far we have seen, exception is beyond developer'due south command. But blaming your code failure on environmental issues is not a solution. Y'all need a Robust Programming, which takes intendance of exceptional situations. Such code is known as Exception Handler.
In our example, good exception treatment would exist, when the server is down, connect to the backup server.
To implement this, enter your code to connect to the server (Using traditional if and else conditions).
You will check if the server is downward. If yes, write the code to connect to the backup server.
Such organization of code, using "if" and "else" loop is not effective when your code has multiple java exceptions to handle.
class connect{ if(Server Up){ // code to connect to server } else{ // code to connect to Fill-in server } }
Attempt Grab Block
Java provides an inbuilt exceptional treatment.
- The normal code goes into a Effort block.
- The exception handling code goes into the Catch cake
In our instance, TRY block will comprise the code to connect to the server. Catch cake will contain the lawmaking to connect to the backup server.
In case the server is upward, the code in the Take hold of cake will be ignored. In case the server is down, an exception is raised, and the code in catch block will be executed.
So, this is how the exception is handled in Java.
Syntax for using attempt & take hold of
try{ statement(s) } catch (exceptiontype name){ statement(south) }
Example
Footstep 1) Copy the post-obit code into an editor
class JavaException { public static void chief(String args[]){ int d = 0; int n = 20; int fraction = n/d; Organisation.out.println("End Of Master"); } }
Footstep 2) Save the file & compile the code. Run the programme using command, java JavaException
Footstep 3) An Arithmetics Exception – carve up by zero is shown as below for line # 5 and line # 6 is never executed
Step 4) Now let's see examine how try and take hold of will assistance united states of america to handle this exception. We will put the exception causing the line of code into a try block, followed by a take hold of block. Copy the following code into the editor.
course JavaException { public static void main(Cord args[]) { int d = 0; int due north = xx; try { int fraction = north / d; System.out.println("This line volition non be Executed"); } take hold of (ArithmeticException eastward) { System.out.println("In the grab Block due to Exception = " + e); } System.out.println("End Of Master"); } }
Pace five) Salve, Compile & Run the code.Y'all will get the following output
As you observe, the exception is handled, and the terminal line of code is also executed. Also, note that Line #seven will non exist executed because as soon equally an exception is raised the menstruum of command jumps to the catch cake.
Note: The AritmeticException Object "e" carries information well-nigh the exception that has occurred which can be useful in taking recovery actions.
Java Exception grade Hierarchy
Later on one grab statement executes, the others are bypassed, and execution continues subsequently the try/catch block. The nested grab blocks follow Exception hierarchy.
- All exception classes in Java extend the course 'Throwable'. Throwable has two subclasses, Mistake and Exception
- The Mistake class defines the exception or the bug that are not expected to occur under normal circumstances by our program, instance Memory mistake, Hardware fault, JVM error, etc
- The Exception class represents the exceptions that can be handled by our program, and our program tin can be recovered from this exception using endeavour and catch block
- A Runtime exception is a sub-class of the exception class. The Exception of these type represents exception that occur at the run time and which cannot exist tracked at the compile time. An excellent example of aforementioned is divide by zero exception, or aught pointer exception, etc
- IO exception is generated during input and output operations
- Interrupted exceptions in Java, is generated during multiple threading.
Case: To understand nesting of endeavor and catch blocks
Step ane) Copy the following code into an editor.
grade JavaException { public static void main(Cord args[]) { attempt { int d = 1; int northward = 20; int fraction = n / d; int g[] = { 1 }; grand[20] = 100; } /*catch(Exception east){ System.out.println("In the grab block due to Exception = "+e); }*/ catch (ArithmeticException east) { System.out.println("In the catch block due to Exception = " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("In the take hold of cake due to Exception = " + e); } System.out.println("End Of Main"); } }
Step 2) Save the file & compile the code. Run the plan using command, java JavaException.
Footstep 3) An ArrayIndexOutOfBoundsException is generated. Change the value of int d to 0. Salvage, Compile & Run the lawmaking.
Step 4) An ArithmeticException must be generated.
Step 5) Uncomment line #10 to line #12. Save, Compile & Run the code.
Step half dozen) Compilation Fault? This is because Exception is the base class of ArithmeticException Exception. Any Exception that is raised past ArithmeticException can be handled by Exception form as well.So the catch cake of ArithmeticException will never get a run a risk to exist executed which makes it redundant. Hence the compilation error.
Java Finally Block
The finally cake is executed irrespective of an exception being raised in the try block. It is optional to use with a try block.
endeavor { argument(s) } catch (ExceptiontType name) { argument(southward) } finally { statement(s) }
In case, an exception is raised in the effort block, finally cake is executed after the grab block is executed.
Example
Step 1) Copy the post-obit code into an editor.
grade JavaException { public static void main(String args[]){ effort{ int d = 0; int due north =20; int fraction = n/d; } grab(ArithmeticException eastward){ System.out.println("In the catch cake due to Exception = "+eastward); } finally{ Organization.out.println("Inside the finally block"); } } }
Step 2) Save, Compile & Run the Code.
Step 3) Expected output. Finally cake is executed fifty-fifty though an exception is raised.
Footstep 4) Alter the value of variable d = 1. Relieve, Compile and Run the code and observe the output.Bottom of Form
Summary:
- An Exception is a run-time error which interrupts the normal menstruation of program execution.Disruption during the execution of the plan is referred as mistake or exception.
- Errors are classified into two categories
- Compile fourth dimension errors – Syntax errors, Semantic errors
- Runtime errors- Exception
- A robust program should handle all exceptions and continue with its normal flow of program execution. Java provides an inbuilt exceptional handling method
- Exception Handler is a ready of lawmaking that handles an exception. Exceptions can be handled in Java using try & catch.
- Try block: Normal code goes on this block.
- Catch block: If in that location is fault in normal code, and then it will go into this cake
Source: https://www.guru99.com/java-exception-handling.html
- Get link
- Other Apps
Comments
Post a Comment