SlideShare a Scribd company logo
1 of 18
EXCEPTION HANDLING IN JAVA
JAVA PROGRAMMING
Mrs.N.Kavitha
Head & Assistant Professor,
Department of Computer Science,
EMG Yadava Women’s College,
Madurai.
EXCEPTION HANDLING IN JAVA
• Exception handling is one of the most important feature of java programming that allows us
to handle the runtime errors caused by exceptions.
• What is an exception?
• An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system
generated error message. The good thing about exceptions is that they can be handled in
Java. By handling the exceptions we can provide a meaningful message to the user about the
issue rather than a system generated message, which may not be understandable to a user.
• Why an exception occurs?
• There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection problem, bad
input data provided by user etc.
• Exception Handling
• If an exception occurs, which has not been handled by programmer then
program execution gets terminated and a system generated error message
is shown to the user.
• Advantage of exception handling
Exception handling ensures that the flow of the program doesn’t break
when an exception occurs.
For example, if a program has bunch of statements and an exception
occurs mid way after executing certain statements then the statements
after the exception will not execute and the program will terminate
abruptly.
By handling we make sure that all the statements execute and the flow of
program doesn’t break.
• Difference between error and exception
• Errors indicate that something severe enough has gone wrong, the
application should crash rather than try to handle the error.
• Exceptions are events that occurs in the code. A programmer can
handle such conditions and take necessary corrective actions.
Examples:
NullPointerException – When you try to use a reference that points
to null.
ArithmeticException – To divide a number by zero this exception
occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – To access the elements of an
array out of its bounds, for example array size is 5 (which means it has
five elements) and you are trying to access the 10th element.
• Types of exceptions
• There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
• Checked and Unchecked exceptions in Java.
• Checked exceptions
All exceptions other than Runtime Exceptions are known as
Checked exceptions as the compiler checks them during compilation
to see whether the programmer has handled them or not.
If these exceptions are not handled/declared in the program, you will
get compilation error.
For example, SQLException, IOException,ClassNotFoundException
etc.
Unchecked Exceptions:
Runtime Exceptions are also known as Unchecked Exceptions.
These exceptions are not checked at compile-time so compiler does not
check whether the programmer has handled them or not but it’s the
responsibility of the programmer to handle these exceptions and
provide a safe exit.
For example, ArithmeticException, NullPointerException, Array Index
out of Bounds Exception etc.
Compiler will never force you to catch such exception or force you to
declare it in the method using throws keyword.
TRY CATCH block
Try block:
The try block contains set of statements where an exception can occur.
 A try block is always followed by a catch block, which handles the exception
that occurs in associated try block.
A try block must be followed by catch blocks or finally block or both.
While writing a program, if you think that certain statements in a program can
throw a exception, enclosed them in try block and handle that exception
Syntax of try block:
try{ //statements that may cause an exception }
Catch block
A catch block is where you handle the exceptions, this block must follow the try
block.
A single try block can have several catch blocks associated with it.
You can catch different exceptions in different catch blocks.
 When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes.
For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes
Syntax of try catch in java
try
{ //statements that may cause an exception }
catch (exception(type) e(object))
{ //error handling code }
class Example1
{
public static void main(String args[])
{
int num1, num2;
try
{
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
catch (Exception e)
{
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Multiple catch blocks in Java:
1. A single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions.
Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of
them.
Example of Multiple catch blocks
class Example2
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e)
{
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e)
{
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Finally Block:
A finally block contains all the crucial statements that must be executed whether exception occurs or not.
 The statements present in this block will always execute regardless of whether exception occurs in try block or
not such as closing a connection, stream etc.
Syntax of Finally block:
try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}
A Simple Example of finally block
class Example
{
public static void main(String args[])
{
try
{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e)
{
System.out.println("Number should not be divided by zero");
}
finally
{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Throwing our own Exception:
We can define our own set of conditions or rules and throw an
exception explicitly using throw keyword.
 For example, we can throw ArithmeticException when we divide
number by 5, or any other numbers, what we need to do is just set the
condition and throw any exception using throw keyword.
 Throw keyword can also be used for throwing custom exceptions.
Syntax of throw keyword:
throw new exception_class("error message");
public class ThrowExample
{
static void checkEligibilty(int stuage, int stuweight)
{
if(stuage<12 && stuweight<40)
{
throw new ArithmeticException("Student is not eligible for registration");
}
else
{
System.out.println("Student Entry is Valid!!");
}
}
public static void main(String args[])
{
System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}
Output:
Welcome to the Registration process!!
java.lang.ArithmeticException:
13,42
Student is not eligible for registration

More Related Content

What's hot (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception Handling In Java 15734
Exception Handling In Java 15734Exception Handling In Java 15734
Exception Handling In Java 15734
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
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
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 

Similar to Exception handling in java

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.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 

Similar to Exception handling in java (20)

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
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Exception handling
Exception handlingException handling
Exception handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 

More from Kavitha713564

THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptxKavitha713564
 
The Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxThe Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxKavitha713564
 
Programming in python in detail concept .pptx
Programming in python in detail concept .pptxProgramming in python in detail concept .pptx
Programming in python in detail concept .pptxKavitha713564
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxKavitha713564
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Arrays,string and vector
Arrays,string and vectorArrays,string and vector
Arrays,string and vectorKavitha713564
 

More from Kavitha713564 (14)

THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
 
The Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxThe Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptx
 
Programming in python in detail concept .pptx
Programming in python in detail concept .pptxProgramming in python in detail concept .pptx
Programming in python in detail concept .pptx
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptx
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptx
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Applet in java new
Applet in java newApplet in java new
Applet in java new
 
Basic of java
Basic of javaBasic of java
Basic of java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Arrays,string and vector
Arrays,string and vectorArrays,string and vector
Arrays,string and vector
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Exception handling in java

  • 1. EXCEPTION HANDLING IN JAVA JAVA PROGRAMMING Mrs.N.Kavitha Head & Assistant Professor, Department of Computer Science, EMG Yadava Women’s College, Madurai.
  • 2. EXCEPTION HANDLING IN JAVA • Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. • What is an exception? • An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user. • Why an exception occurs? • There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc.
  • 3. • Exception Handling • If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. • Advantage of exception handling Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly. By handling we make sure that all the statements execute and the flow of program doesn’t break.
  • 4. • Difference between error and exception • Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error. • Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions. Examples: NullPointerException – When you try to use a reference that points to null. ArithmeticException – To divide a number by zero this exception occurs because dividing a number by zero is undefined. ArrayIndexOutOfBoundsException – To access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.
  • 5.
  • 6. • Types of exceptions • There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions • Checked and Unchecked exceptions in Java. • Checked exceptions All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException,ClassNotFoundException etc.
  • 7. Unchecked Exceptions: Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, Array Index out of Bounds Exception etc. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword.
  • 8. TRY CATCH block Try block: The try block contains set of statements where an exception can occur.  A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both. While writing a program, if you think that certain statements in a program can throw a exception, enclosed them in try block and handle that exception Syntax of try block: try{ //statements that may cause an exception }
  • 9. Catch block A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks.  When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes Syntax of try catch in java try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }
  • 10. class Example1 { public static void main(String args[]) { int num1, num2; try { num1 = 0; num2 = 62 / num1; System.out.println(num2); System.out.println("Hey I'm at the end of try block"); } catch (ArithmeticException e) { System.out.println("You should not divide a number by zero"); } catch (Exception e) { System.out.println("Exception occurred"); } System.out.println("I'm out of try-catch block in Java."); } }
  • 11. Multiple catch blocks in Java: 1. A single try block can have any number of catch blocks. 2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them.
  • 12. Example of Multiple catch blocks class Example2 { public static void main(String args[]) { try { int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e) { System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e) { System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } }
  • 13. Finally Block: A finally block contains all the crucial statements that must be executed whether exception occurs or not.  The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc. Syntax of Finally block: try { //Statements that may cause an exception } catch { //Handling exception } finally { //Statements to be executed }
  • 14. A Simple Example of finally block class Example { public static void main(String args[]) { try { int num=121/0; System.out.println(num); } catch(ArithmeticException e) { System.out.println("Number should not be divided by zero"); } finally { System.out.println("This is finally block"); } System.out.println("Out of try-catch-finally"); } }
  • 15. Output: Number should not be divided by zero This is finally block Out of try-catch-finally
  • 16. Throwing our own Exception: We can define our own set of conditions or rules and throw an exception explicitly using throw keyword.  For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what we need to do is just set the condition and throw any exception using throw keyword.  Throw keyword can also be used for throwing custom exceptions. Syntax of throw keyword: throw new exception_class("error message");
  • 17. public class ThrowExample { static void checkEligibilty(int stuage, int stuweight) { if(stuage<12 && stuweight<40) { throw new ArithmeticException("Student is not eligible for registration"); } else { System.out.println("Student Entry is Valid!!"); } } public static void main(String args[]) { System.out.println("Welcome to the Registration process!!"); checkEligibilty(10, 39); System.out.println("Have a nice day.."); } }
  • 18. Output: Welcome to the Registration process!! java.lang.ArithmeticException: 13,42 Student is not eligible for registration