An exception is an unwanted or unexpected event that occurs during program execution, i.e. at runtime, disrupting the normal flow of instructions from the program.
An Error indicates a serious problem that a reasonable application should not try to catch. It’s an issue and needs to be fixed.An exception is a condition that a reasonable application might try to catch or handle.
Below is a class hierarchy of exception classes:
All types of exceptions and errors are subclasses of the Throwable class, which is the hierarchy base class. Exception leads to one branch. This class is used for exceptional conditions that user programs should catch. Example: NullPointerException.
Another branch, the Java run-time system(JVM) uses Error to show mistakes related to the run-time setting (JRE) itself. Example: StackOverflowError
Default Exception Handling by Java: Whenever an exception has occurred inside a method, the method creates an object known as an exception object and transfers it to the runtime system(JVM). The exception object includes the exception name and description, and the present program states where an exception happened. It is called throwing an exception to create the exception object and handle it to the run-time system. There might be a list of methods called to get to the method where there was an exception. Call Stack is called this ordered list of methods.
Now the following procedure will happen.
See the diagram below to comprehend the call stack's flow.
Customized Exception Handling in java: Five keywords are used to manage Java exception handling: try, catch, throw, throws and finally. Briefly, the way they operate is here. Statements of the program that you believe may raise exceptions are contained in a try block. If there is an exception within the try block, it will be thrown. Your software can capture and manage this exception in some rational way (using the catch block). The Java runtime system automatically throws system-generated exceptions. Use the keyword throw to manually insert an exception. Any exception that is thrown from a method must be defined by a throws clause as such. Any code that must be performed after completing a try block is placed in a final block.
Below is an example as how to use try-catch clause:
try { // the code you think can throw an exception } catch (Exception1 ex1) { // exception handler for Exception1 } catch (Exception2 ex2) { // exception handler for Exception2 } finally { // block of code to be executed after try block ends whether exception occurred or not. }
Points to remember in exception handling in java:
Summary:
Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.
Thank you for your valuable information.
Thank you for this wonderful article!
This article was really helpful to me, thank you!
super article!
Leave a Reply
Your email address will not be published. Required fields are marked *