SlideShare a Scribd company logo
1 of 26
Divyavani,Assistant Professor 1
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
Exception Handling in Java
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called
the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception
occurred.
Divyavani,Assistant Professor 2
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
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running
out of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc. Errors are usually beyond the control of the programmer, and we should
not try to handle errors.
differences between Error and Exception
Error: An Error indicates a serious problem that a reasonable application should not
try to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
Divyavani,Assistant Professor 3
Exception-Handling Fundamentals
 A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code.
 When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
 That method may choose to handle the exception itself, or pass it on. Either
way, at some point, the exception is caught and processed.
 Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
Divyavani,Assistant Professor 4
 Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally.
 Program statements that you want to monitor for exceptions are contained within a
try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in some rational
manner.
 System-generated exceptions are automatically thrown by the Java run-time
system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws
clause.
Divyavani,Assistant Professor 5
1. try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A
try block is always followed by a catch block, which handles the exception that
occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
Divyavani,Assistant Professor 6
3. throw: The throw keyword is used to transfer control from the try block
to the catch block.
4. throws: The throws keyword is used for exception handling without try
& catch block. It specifies the exceptions that a method can throw to the
caller and does not handle itself.
5. finally: It is executed after the catch block. We use it to put some
common code (to be executed irrespective of whether an exception has
occurred or not ) when there are multiple catch blocks.
Divyavani,Assistant Professor 7
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed after try block ends
}
Divyavani,Assistant Professor 8
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
} Divyavani,Assistant Professor 9
class ThrowsExecp {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
Divyavani,Assistant Professor 10
Divyavani,Assistant Professor 11
throw, throws, and finally keywords in Java
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters the throw keyword,
it stops the execution of try block and jump to the corresponding catch block.
 Using throw keyword only object of Throwable class or its sub classes
can be thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by an throwable instance.
Syntax
throw instance;
Here the instace must be throwable instance
and it can be created dynamically using new
operator.
Divyavani,Assistant Professor 12
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new
ArithmeticException("Division by zero is not
posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2
+ "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 13
throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
🔔 When a method throws an exception, we must put the calling statement
of method in try-catch block.
import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" +
result);
}
public static void main(String[] args) {
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 14
Important Points to Remember about throws Keyword
 throws keyword is required only for checked exceptions and usage of the
throws keyword for unchecked exceptions is meaningless.
 throws keyword is required only to convince the compiler and usage of the
throws keyword does not prevent abnormal termination of the program.
 With the help of the throws keyword, we can provide information to the caller
of the method about the exception.
Divyavani,Assistant Professor 15
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
🔔 Only one finally block is allowed for each try block.
🔔 Use of finally block is optional.
Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Divyavani,Assistant Professor 16
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Divyavani,Assistant Professor 17
import java.util.Scanner;
public class FinallyExample {
public static void main(String[] args) {
int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two
numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new
ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2
+ "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
finally {
System.out.println("The finally block
executes always");
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 18
When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try block
and then the program terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try
block");
//below code throws divide by zero
exception
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception
occured or not
finally {
System.out.println("finally block is
always executed");
}
System.out.println("rest of the code...");
}
}
Divyavani,Assistant Professor 19
Sr. no. Basis of Differences throw throws
1. Definition Java throw keyword is used
throw an exception explicitly
in the code, inside the
function or the block of
code.
Java throws keyword is
used in the method
signature to declare an
exception which might be
thrown by the function while
the execution of the code.
2. Type of exception Using
throw keyword, we can only
propagate unchecked
exception i.e., the checked
exception cannot be
propagated using throw
only.
Using throws keyword, we
can declare both checked
and unchecked exceptions.
However, the throws
keyword can be used to
propagate checked
exceptions only.
3. Syntax The throw keyword is
followed by an instance of
Exception to be thrown.
The throws keyword is
followed by class names of
Exceptions to be thrown.
4. Declaration throw is used within the
method.
throws is used with the
method signature.
5. Internal implementation We are allowed to throw
only one exception at a time
i.e. we cannot throw
multiple exceptions.
We can declare multiple
exceptions using throws
keyword that can be thrown
by the method. For
example, main() throws
Divyavani,Assistant Professor 20
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("nNumber is negative, cannot
calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
} Divyavani,Assistant Professor 21
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
} Divyavani,Assistant Professor 22
Exception Hierarchy
All exception and error types are subclasses of
class Throwable, which is the base class of the
hierarchy.
One branch is headed by Exception. This class is
used for exceptional conditions that user
programs should catch. NullPointerException is
an example of such an exception.
Another branch, Error is used by the Java run-
time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE).
StackOverflowError is an example of such an
error.
Divyavani,Assistant Professor 23
Types of Exceptions
Divyavani,Assistant Professor 24
Exceptions can be categorized in two ways:
1. Built-in Exceptions
a) Checked Exception
b) Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
The following are a few built-in classes used to handle checked exceptions in java.
 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
Divyavani,Assistant Professor 25
import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:UsersUserDesktopTodaySample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
Divyavani,Assistant Professor 26

More Related Content

Similar to Exception Hnadling java programming language

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingGovindanS3
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 

Similar to Exception Hnadling java programming language (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 

Recently uploaded

EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 

Recently uploaded (20)

EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 

Exception Hnadling java programming language

  • 2. The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Exception Handling in Java What is Exception in Java? Dictionary Meaning: Exception is an abnormal condition. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred. Divyavani,Assistant Professor 2
  • 3. 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 Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors. differences between Error and Exception Error: An Error indicates a serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch. Divyavani,Assistant Professor 3
  • 4. Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.  Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Divyavani,Assistant Professor 4
  • 5.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  Program statements that you want to monitor for exceptions are contained within a try block.  If an exception occurs within the try block, it is thrown.  Your code can catch this exception (using catch) and handle it in some rational manner.  System-generated exceptions are automatically thrown by the Java run-time system.  To manually throw an exception, use the keyword throw.  Any exception that is thrown out of a method must be specified as such by a throws clause. Divyavani,Assistant Professor 5
  • 6. 1. try: The try block contains a set of statements where an exception can occur. try { // statement(s) that might cause exception } 2. catch: The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. catch { // statement(s) that handle an exception // examples, closing a connection, closing // file, exiting the process after writing // details to a log file. } Divyavani,Assistant Professor 6
  • 7. 3. throw: The throw keyword is used to transfer control from the try block to the catch block. 4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. 5. finally: It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks. Divyavani,Assistant Professor 7
  • 8. This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } finally { // block of code to be executed after try block ends } Divyavani,Assistant Professor 8
  • 9. class Division { public static void main(String[] args) { int a = 10, b = 5, c = 5, result; try { result = a / (b - c); System.out.println("result" + result); } catch (ArithmeticException e) { System.out.println("Exception caught:Division by zero"); } finally { System.out.println("I am in final block"); } } } Divyavani,Assistant Professor 9
  • 10. class ThrowsExecp { static void fun() throws IllegalAccessException { System.out.println("Inside fun(). "); throw new IllegalAccessException("demo"); } // This is a caller function public static void main(String args[]) { try { fun(); } catch (IllegalAccessException e) { System.out.println("caught in main."); } } } Divyavani,Assistant Professor 10
  • 12. throw, throws, and finally keywords in Java throw keyword in Java The throw keyword is used to throw an exception instance explicitly from a try block to corresponding catch block. That means it is used to transfer the control from try block to corresponding catch block. The throw keyword must be used inside the try blcok. When JVM encounters the throw keyword, it stops the execution of try block and jump to the corresponding catch block.  Using throw keyword only object of Throwable class or its sub classes can be thrown. Using throw keyword only one exception can be thrown. The throw keyword must followed by an throwable instance. Syntax throw instance; Here the instace must be throwable instance and it can be created dynamically using new operator. Divyavani,Assistant Professor 12
  • 13. import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1, num2, result; System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); try { if(num2 == 0) throw new ArithmeticException("Division by zero is not posible"); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } System.out.println("End of the program"); } } Divyavani,Assistant Professor 13
  • 14. throws keyword in Java The throws keyword specifies the exceptions that a method can throw to the default handler and does not handle itself. That means when we need a method to throw an exception automatically, we use throws keyword followed by method declaration 🔔 When a method throws an exception, we must put the calling statement of method in try-catch block. import java.util.Scanner; public class ThrowsExample { int num1, num2, result; Scanner input = new Scanner(System.in); void division() throws ArithmeticException { System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } public static void main(String[] args) { try { new ThrowsExample().division(); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } System.out.println("End of the program"); } } Divyavani,Assistant Professor 14
  • 15. Important Points to Remember about throws Keyword  throws keyword is required only for checked exceptions and usage of the throws keyword for unchecked exceptions is meaningless.  throws keyword is required only to convince the compiler and usage of the throws keyword does not prevent abnormal termination of the program.  With the help of the throws keyword, we can provide information to the caller of the method about the exception. Divyavani,Assistant Professor 15
  • 16. finally keyword in Java The finally keyword used to define a block that must be executed irrespective of exception occurence. The basic purpose of finally keyword is to cleanup resources allocated by try block, such as closing file, closing database connection, etc. 🔔 Only one finally block is allowed for each try block. 🔔 Use of finally block is optional. Rule: For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort). Divyavani,Assistant Professor 16
  • 17. Syntax try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } Divyavani,Assistant Professor 17
  • 18. import java.util.Scanner; public class FinallyExample { public static void main(String[] args) { int num1, num2, result; Scanner input = new Scanner(System.in); System.out.print("Enter any two numbers: "); num1 = input.nextInt(); num2 = input.nextInt(); try { if(num2 == 0) throw new ArithmeticException("Division by zero"); result = num1 / num2; System.out.println(num1 + "/" + num2 + "=" + result); } catch(ArithmeticException ae) { System.out.println("Problem info: " + ae.getMessage()); } finally { System.out.println("The finally block executes always"); } System.out.println("End of the program"); } } Divyavani,Assistant Professor 18
  • 19. When an exception occurr but not handled by the catch block Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally. public class TestFinallyBlock1{ public static void main(String args[]){ try { System.out.println("Inside the try block"); //below code throws divide by zero exception int data=25/0; System.out.println(data); } catch(NullPointerException e){ System.out.println(e); } //executes regardless of exception occured or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Divyavani,Assistant Professor 19
  • 20. Sr. no. Basis of Differences throw throws 1. Definition Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code. Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code. 2. Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only. Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only. 3. Syntax The throw keyword is followed by an instance of Exception to be thrown. The throws keyword is followed by class names of Exceptions to be thrown. 4. Declaration throw is used within the method. throws is used with the method signature. 5. Internal implementation We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions. We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws Divyavani,Assistant Professor 20
  • 21. public class TestThrow { //defining a method public static void checkNum(int num) { if (num < 1) { throw new ArithmeticException("nNumber is negative, cannot calculate square"); } else { System.out.println("Square of " + num + " is " + (num*num)); } } //main method public static void main(String[] args) { TestThrow obj = new TestThrow(); obj.checkNum(-3); System.out.println("Rest of the code.."); } } Divyavani,Assistant Professor 21
  • 22. public class TestThrows { //defining a method public static int divideNum(int m, int n) throws ArithmeticException { int div = m / n; return div; } //main method public static void main(String[] args) { TestThrows obj = new TestThrows(); try { System.out.println(divideNum(45, 0)); } catch (ArithmeticException e){ System.out.println("nNumber cannot be divided by 0"); } System.out.println("Rest of the code.."); } } Divyavani,Assistant Professor 22
  • 23. Exception Hierarchy All exception and error types are subclasses of class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run- time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error. Divyavani,Assistant Professor 23
  • 25. Exceptions can be categorized in two ways: 1. Built-in Exceptions a) Checked Exception b) Unchecked Exception 2. User-Defined Exceptions 1. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. The following are a few built-in classes used to handle checked exceptions in java.  IOException  FileNotFoundException  ClassNotFoundException  SQLException  DataAccessException  InstantiationException Divyavani,Assistant Professor 25
  • 26. import java.io.*; public class CheckedExceptions { public static void main(String[] args) { File f_ref = new File("C:UsersUserDesktopTodaySample.txt"); try { FileReader fr = new FileReader(f_ref); }catch(Exception e) { System.out.println(e); } } } Divyavani,Assistant Professor 26