Exception Handling in Java

 Exception Handling in java 


Exception handling in Java allows you to handle runtime errors or exceptional conditions that may occur during the execution of a program.

-All the exceptions occur only at runtime. A syntax error occurs at compile time.

     

Exception  : Exception is an unwanted or unexpected behaviour/event which occurs during the execution of a program at run time.


Purpose of Exception Handling

graceful termination of the program is the Purpose of Exception Handling 

Ex - power off 


What is Exception Handling

Definating alternative way to continue rest of program Normaly is nothing but exception Handling.


Ex1 - Specific Movie ticket then change watch another movie.

Ex2 - Save the data a before power cut . 


 Major reasons why an exception Occurs

Invalid user input

Device failure

Loss of network connection

Physical limitations (out of disk memory)

Code errors

Opening an unavailable file 

When a user attempts to divide an integer value by zero, an exception occurs.


Differenece between Error & Exception 

Errors are usually caused by serious problems that cannot be recovered from, while exceptions are used to handle recoverable errors within a program.



Default Exception Handling in Java

Def : if any exception not handle by anyone then default exception handler print  the exception Name , Description & Stack trace/location on console and JVM terminate the program abnormally. 

Normal Termination : those method exceuted Normally then thats termanation as known as  Normal termination.

AbNormal Termination : if any single method exceuted  abNormally then thats termination as known abNormal termination.


How does Exception handling mechanism work?

The main purpose of using exception handling mechanism in a java program is to handle unexpected errors and maintain the normal flow of the program.




Exception Hierarchy in Java

Types of Exceptions in Java

Basically, there are two types of exceptions in java API. They are:

1.Predefined Exceptions (Built-in-Exceptions)

2.Custom Exceptions (user define exeception)


1.Predefined Exceptions (Built-in-Exceptions)

Predefined exceptions are those exceptions that are already defined by Java system. 

These exceptions are also called built-in-exceptions


The Throwable class is the root of exception hierarchy and is an immediate subclass of Object class. Let’s understand the java exception hierarchy, as shown in the below figure.


1. Throwable class:  

  • It is the root of all exception classes. It is present in java.lang package.
  • Throwable class is the superclass of all exceptions in java. This class has two subclasses: Error and Exception.


2. Error:  

  • Error is an unusual problem or situation  which is not able recoverable.
  •   It does not occur by programmer mistakes. 
  • It generally occurs if the system is not working properly or resource is not allocated properly.


3. Exception: 

  • Exceptions are used to handle recoverable errors within a program.




2.Custom Exceptions (user define exeception)
- Custom exceptions are those exceptions that are created by users or programmers according to             their own needs. 
- The custom exceptions are also called user-defined exceptions that are created by extending the             exception class.


Checked and Unchecked Exceptions 

All the predefined exceptions are divided into two groups:
1.Checked Exceptions (Ex - Id )
2.Unchecked Exceptions



1.Checked Exceptions  

Checked exceptions are those exceptions that are checked by the java compiler at time compilation is known as Checked Exception.

 

2.Unchecked Exceptions

Unchecked exceptions in Java are those exceptions that are checked by JVM, not by java compiler. They occur during the runtime of a program.

All exceptions under the runtime exception class are called unchecked exceptions or runtime exceptions in Java.


Five keywords to handle Exception in Java

The process of creating an exception object and handing it to runtime system is called throwing an exception in java.

After a method throws an exception, JVM searches for a method in the call stack that contains a block of code that handles the exception. 

This process is called catching an exception.

A block of code that catches the exception thrown by JVM is called exception handler. This whole mechanism is called exception handling in Java.


Java provides five essential keywords to handle an exception. They are as:

try

catch

finally

throw

throws


try Block:

- A keyword “try” is a block of code or statements that might throw an exception. That’s why a try block is also known as exception generated block.

- We should place exception generated code (risky code) inside try block. 

- The try block must be followed by either catch or finally.


The three possible forms of try block are as follows:

try-catch: A try block is always followed by one or more catch blocks.

try-finally: A try block followed by a finally block.

try-catch-finally: A try block followed by one or more catch blocks followed by a finally block.


Catch Block :

- A keyword “catch” is a block of code that handles the exception thrown by the try block. That’s why it is also known as exception handler block.

- A catch block that catches an exception, must be followed by try block that generates an exception.

- When statements in a single try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This mechanism is called multi-catch block in java.


finally block :

finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.

Rules : 

1. A finally block is optional but at least one of the catch or finally block must exist with a try.

2. It must be defined at the end of last catch block. If finally block is defined before a catch block, the program will not compile successfully.

3. Unlike catch, multiple finally blocks cannot be declared with a single try block. That is there can be only one finally clause with a single try block.

4. Note: The finally block may not execute if the JVM exits while the try or catch code is being executed.


Throw Keyword :

- Throw in Java is a keyword that is used to throw a built-in exception or a custom exception explicitly or manually. Using throw keyword, we can throw either checked or unchecked exceptions in Java programming.

- When an exception occurs in the try block, throw keyword transfers the control of execution to the caller by throwing an object of exception.

- Only one object of exception type can be thrown by using throw keyword at a time. Throw keyword can be used inside a method or static block provided that exception handling is present.


For example:

1. throw new ArithmeticException();

Or,

ArithmeticException ae = new ArithmeticException();

throw ae;


Throws Keyword in Java

Throws keyword in Java is used in the method declaration. It provides information to the caller method about exceptions being thrown and the caller method has to take the responsibility of handling the exception.

throws keyword is used in case of checked exception only because if we are not handling runtime exceptions (unchecked exceptions)




Diffrent between final ,finally & finalize.

Definition

final  :final is the keyword and access modifier which is used to apply restrictions on a class, method or variable.                                                                                                                                           finally : finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not.

finalize  : finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.





Comments

Popular Posts