SlideShare a Scribd company logo
JAVA
Exception
Handling
Prepared by
Miss. Arati A. Gadgil
2
Errors and Error Handling
An Error is any unexpected result obtained from a program during
execution.
Unhandled errors may manifest themselves as incorrect results or
behavior, or as abnormal program termination.Errors should be handled
by the programmer.
Traditional Error Handling
1.Every method returns a value (flag) indicating either success, failure,
or some error condition. The calling method checks the return flag and
takes appropriate action.
Downside: programmer must remember to always check the return
value and take appropriate action. This requires much code (methods
are harder to read) and something may get overlooked.
3
Traditional Error Handling
2. Create a global error handling routine, and use some form of
“jump” instruction to call this routine when an error occurs.
Downside: “jump” instruction (GoTo) are considered “bad
programming practice” and are discouraged. Once you jump to the
error routine, you cannot return to the point of origin and so must
(probably) exit the program.
Exceptions act similar to method return flags in that any method may
raise and exception should it encounter an error.
Exceptions act like global error methods in that the exception
mechanism is built into Java; exceptions are handled at many levels
in a program, locally and/or globally.
Exception
Due to design errors or coding errors, our programs may fail in
unexpected ways during execution.
It is our responsibility to produce quality code that does not fail
unexpectedly.
Consequently, we must design error handling into our programs.
An exception is a special type of error object that is created when
something goes wrong in a program.
After Java creates the exception object, it sends it to program, this action
called throwing an exception. It's up to our program to catch the
exception.
5
An exception is a representation of an error condition or a situation
that is not the expected result of a method.
Exceptions are built into the Java language and are available to all
program code.
Exceptions isolate the code that deals with the error condition from
regular program logic.
When an error is detected, an exception is thrown
Any exception which is thrown, must be caught by and exception
handler
If the programmer hasn't provided one, the exception will be caught
by a catch-all exception handler provided by the system.
6
The default exception handler may terminate the application.
Exceptions can be rethrown if the exception cannot be handled by the
block which caught the exception
Java has 5 keywords for exception handling:
1.try
2.catch
3.finally
4.throw
5.Throws
7
Exception -Class Hierarchy
Throwable
+ Throwable(String message)
+ getMessage(): String
+ printStackTrace():void
Error Exception
Errors: An error represents a condition
serious enough that most reasonable
applications should not try to catch.
- Virtual Machine Error
- out of memory
- stack overflow
- Thread Death
- Linkage Error
Exceptions: An error which reasonable
applications should catch
- Array index out of bounds
- Arithmetic errors (divide by zero)
- Null Pointer Exception
- I/O Exceptions
See the Java API Specification for more.
8
Exceptions -Checked and Unchecked
Java allows for two types of exceptions:
1.Checked.
If your code invokes a method which is defined to throw checked
exception, your code MUST provide a catch handler
The compiler generates an error if the appropriate catch handler is not
Present
2.Unchecked
These exceptions can occur through normal operation of the virtual
machine. You can choose to catch them or not.
If an unchecked exception is not caught, it will go to the default catch-all
handler for the application
All Unchecked exceptions are subclassed from RuntimeException
9
Common Java Exceptions.
ArithmeticException :Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException:Caused by bad array indexes
ArrayStoreException: Caused when a program tries to store the wrong
type of data in an array
FileNotFoundException: Caused by an attempt to access a nonexistent
file
IOException: Caused by general I/O failures, such as inability to read
from a file
NullPointerException: Caused by referencing a null object
NumberFormatException: Caused when a conversion between strings
and numbers fails
10
OutOfMemoryException: Caused when there's not enough memory to
allocate a new object
SecurityException: Caused when an applet tries to perform an action not
allowed by the browser'ssecurity setting
StackOverflowException: Caused when the system runs out of stack
space
StringIndexOutOfBoundsException:Caused when a program attempts to
access a nonexistent characterposition in a string
11
Exceptions –Syntax
try
{ // Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{ // code to handle a FileNotFound exception }
catch(IOException x)
{ // code to handle any other I/O exceptions }
catch(Exception x)
{ // Code to catch any other type of exception }
finally
{ // This code is ALWAYS executed whether an exception was
thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}
12
Try-Catch Mechanism
Wherever your code may trigger an exception, the normal code logic
is placed inside a block of code starting with the “try” keyword:
After the try block, the code to handle the exception should it arise is
placed in a block of code starting with the “catch” keyword.
You may also write an optional “finally” block. This block contains
code that is ALWAYS executed, either after the “try” block code, or
after the “catch” block code.
Finally blocks can be used for operations that must happen no matter
what (i.e. cleanup operations such as closing a file)
13
throws keyword
The throws keyword is used in method declaration, in order to explicitly
specify the exceptions that a particular method might throw.
When a method declaration has one or more exceptions defined using
throws clause then the method-call must handle all the defined
exceptions.
When defining a method you must include a throws clause to declare
those exceptions that might be thrown but doesn’t get caught in the
method.
If a method is using throws clause along with few exceptions then this
implicitly tells other methods that – “ If you call me, you must handle
these exceptions that I throw”.
Syntax of Throws in java:
void MethodName() throws ExceptionName{ Statement1 ... ... }
14
throw Keyword
By default, when an exception condition occurs the system automatically
throw an exception to inform user that there is something wrong.
However we can also throw exception explicitly based on our own
defined condition.
Using “throw keyword” we can throw checked, unchecked and user
-defined exceptions.
15
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("Entries 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..");
}
}
16
import java.io.*;
class Example
{
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("B:/myfile.txt");
int k;
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}
Declare the exception in the method using throws keyword.
17
import java.io.*;
class Example
{ public static void main(String args[])
{ FileInputStream fis = null;
try{
fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe)
{
System.out.println("The specified file is not exist);
}
int k;
try{
while(( k = fis.read() ) != -1)
{ System.out.print((char)k); }
fis.close();
}catch(IOException ioe)
{ System.out.println("I/O error occurred: "+ioe); }
}
18
Throw vs Throws in java
1. Throws clause in used to declare an exception and thow keyword is
used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance variable
and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception
and throws clause is used in method declaration (signature).
4.By using Throw keyword in java you cannot throw more than one
exception but using throws you can declare multiple exceptions. PFB the
examples.
19
User defined exception
User defined exceptions in java are also known as Custom exceptions.
Most of the times when we are developing an application in java, we
often feel a need to create and throw our own exceptions. These
exceptions are known as User defined or Custom exceptions.
class MyException extends Exception
{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("Output String = "+str1) ;
}
}
20
class CustomException
{
public static void main(String args[])
{
try
{
throw new MyException("Custom");
// I'm throwing user defined custom exception above
} catch(MyException exp)
{
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
}
21
Defining Your Own Exceptions
To define your own exception you must do the following:
Create an exception class to hold the exception data.Your exception class
must subclass "Exception" or another exception class
To create unchecked exceptions, subclass the RuntimeException class.
Minimally, your exception class should provide a constructor which takes
the exception description as its argument.
To throw your own exceptions:
If your exception is checked, any method which is going to throw the
exception must define it using the throws keyword
When an exceptional condition occurs, create a new instance of the
exception and throw it.
22
Rethrowing Exceptions 
M2() throws an exception and M1() handles it and then rethrows it.
class MyException extends Exception { }
public class RethrowException 
{   
public static void main(String[] args) 
{   try 
       { M1(); } 
          catch (Exception e) 
    { System.out.println("main(): Caught " + e.toString()); }
  }   
public static void M1() throws MyException 
{   try 
       { M2(); } 
23
catch (Exception e) 
    {  
System.out.println("M1(): Caught e.toString());      
                     System.out.println("M1(): Rethrowing " + e.toString());
                     throw e; 
                } 
             }   
public static void M2() throws MyException 
{
 System.out.println("M2(): Throwing MyException..."); 
throw new MyException(); 
} 
} 
24
Advantages of Exceptions
1: Separating Error-Handling Code from "Regular" Code
2: Propagating Errors Up the Call Stack
3: Grouping and Differentiating Error Types
Thank You
25

More Related Content

What's hot

Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
Mavoori Soshmitha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
Tareq Hasan
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 

What's hot (20)

Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Java threads
Java threadsJava threads
Java threads
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Generics
GenericsGenerics
Generics
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 

Viewers also liked

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Coeducation
CoeducationCoeducation
Coeducationskmaken
 
Effects of TECHNOLOGY
Effects of TECHNOLOGYEffects of TECHNOLOGY
Effects of TECHNOLOGY
Amna Kazim
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Impact of Fast Food
Impact of Fast FoodImpact of Fast Food
Impact of Fast Food
Manpreet Singh Bedi
 
Corruption in pakistan
Corruption in pakistan Corruption in pakistan
Corruption in pakistan
Riaz Gul Sheikh
 

Viewers also liked (7)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Coeducation
CoeducationCoeducation
Coeducation
 
Effects of TECHNOLOGY
Effects of TECHNOLOGYEffects of TECHNOLOGY
Effects of TECHNOLOGY
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Impact of Fast Food
Impact of Fast FoodImpact of Fast Food
Impact of Fast Food
 
Corruption in pakistan
Corruption in pakistan Corruption in pakistan
Corruption in pakistan
 

Similar to Java exception

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
DrRajeshreeKhande
 
Java Exceptions
Java ExceptionsJava Exceptions
Java Exceptions
jalinder123
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertionsphanleson
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
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
SakkaravarthiS1
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 

Similar to Java exception (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Java Exceptions
Java ExceptionsJava Exceptions
Java Exceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
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
Exception handlingException handling
Exception handling
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Exception handling
Exception handlingException handling
Exception handling
 

More from Arati Gadgil

Java adapter
Java adapterJava adapter
Java adapter
Arati Gadgil
 
Java swing
Java swingJava swing
Java swing
Arati Gadgil
 
Java applet
Java appletJava applet
Java applet
Arati Gadgil
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
Arati Gadgil
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
Java thread
Java threadJava thread
Java thread
Arati Gadgil
 
Java networking
Java networkingJava networking
Java networking
Arati Gadgil
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
Arati Gadgil
 
Java package
Java packageJava package
Java package
Arati Gadgil
 
Java interface
Java interfaceJava interface
Java interface
Arati Gadgil
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
Arati Gadgil
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Java class
Java classJava class
Java class
Arati Gadgil
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 

More from Arati Gadgil (16)

Java adapter
Java adapterJava adapter
Java adapter
 
Java swing
Java swingJava swing
Java swing
 
Java applet
Java appletJava applet
Java applet
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
 
Java awt
Java awtJava awt
Java awt
 
Java stream
Java streamJava stream
Java stream
 
Java thread
Java threadJava thread
Java thread
 
Java networking
Java networkingJava networking
Java networking
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Java package
Java packageJava package
Java package
 
Java interface
Java interfaceJava interface
Java interface
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
Java collection
Java collectionJava collection
Java collection
 
Java class
Java classJava class
Java class
 
Java basic
Java basicJava basic
Java basic
 

Recently uploaded

Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 

Recently uploaded (20)

Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 

Java exception

  • 2. 2 Errors and Error Handling An Error is any unexpected result obtained from a program during execution. Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination.Errors should be handled by the programmer. Traditional Error Handling 1.Every method returns a value (flag) indicating either success, failure, or some error condition. The calling method checks the return flag and takes appropriate action. Downside: programmer must remember to always check the return value and take appropriate action. This requires much code (methods are harder to read) and something may get overlooked.
  • 3. 3 Traditional Error Handling 2. Create a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs. Downside: “jump” instruction (GoTo) are considered “bad programming practice” and are discouraged. Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program. Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
  • 4. Exception Due to design errors or coding errors, our programs may fail in unexpected ways during execution. It is our responsibility to produce quality code that does not fail unexpectedly. Consequently, we must design error handling into our programs. An exception is a special type of error object that is created when something goes wrong in a program. After Java creates the exception object, it sends it to program, this action called throwing an exception. It's up to our program to catch the exception.
  • 5. 5 An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. Exceptions isolate the code that deals with the error condition from regular program logic. When an error is detected, an exception is thrown Any exception which is thrown, must be caught by and exception handler If the programmer hasn't provided one, the exception will be caught by a catch-all exception handler provided by the system.
  • 6. 6 The default exception handler may terminate the application. Exceptions can be rethrown if the exception cannot be handled by the block which caught the exception Java has 5 keywords for exception handling: 1.try 2.catch 3.finally 4.throw 5.Throws
  • 7. 7 Exception -Class Hierarchy Throwable + Throwable(String message) + getMessage(): String + printStackTrace():void Error Exception Errors: An error represents a condition serious enough that most reasonable applications should not try to catch. - Virtual Machine Error - out of memory - stack overflow - Thread Death - Linkage Error Exceptions: An error which reasonable applications should catch - Array index out of bounds - Arithmetic errors (divide by zero) - Null Pointer Exception - I/O Exceptions See the Java API Specification for more.
  • 8. 8 Exceptions -Checked and Unchecked Java allows for two types of exceptions: 1.Checked. If your code invokes a method which is defined to throw checked exception, your code MUST provide a catch handler The compiler generates an error if the appropriate catch handler is not Present 2.Unchecked These exceptions can occur through normal operation of the virtual machine. You can choose to catch them or not. If an unchecked exception is not caught, it will go to the default catch-all handler for the application All Unchecked exceptions are subclassed from RuntimeException
  • 9. 9 Common Java Exceptions. ArithmeticException :Caused by math errors such as division by zero ArrayIndexOutOfBoundsException:Caused by bad array indexes ArrayStoreException: Caused when a program tries to store the wrong type of data in an array FileNotFoundException: Caused by an attempt to access a nonexistent file IOException: Caused by general I/O failures, such as inability to read from a file NullPointerException: Caused by referencing a null object NumberFormatException: Caused when a conversion between strings and numbers fails
  • 10. 10 OutOfMemoryException: Caused when there's not enough memory to allocate a new object SecurityException: Caused when an applet tries to perform an action not allowed by the browser'ssecurity setting StackOverflowException: Caused when the system runs out of stack space StringIndexOutOfBoundsException:Caused when a program attempts to access a nonexistent characterposition in a string
  • 11. 11 Exceptions –Syntax try { // Code which might throw an exception // ... } catch(FileNotFoundException x) { // code to handle a FileNotFound exception } catch(IOException x) { // code to handle any other I/O exceptions } catch(Exception x) { // Code to catch any other type of exception } finally { // This code is ALWAYS executed whether an exception was thrown // or not. A good place to put clean-up code. ie. close // any open files, etc... }
  • 12. 12 Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword. You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)
  • 13. 13 throws keyword The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions. When defining a method you must include a throws clause to declare those exceptions that might be thrown but doesn’t get caught in the method. If a method is using throws clause along with few exceptions then this implicitly tells other methods that – “ If you call me, you must handle these exceptions that I throw”. Syntax of Throws in java: void MethodName() throws ExceptionName{ Statement1 ... ... }
  • 14. 14 throw Keyword By default, when an exception condition occurs the system automatically throw an exception to inform user that there is something wrong. However we can also throw exception explicitly based on our own defined condition. Using “throw keyword” we can throw checked, unchecked and user -defined exceptions.
  • 15. 15 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("Entries 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.."); } }
  • 16. 16 import java.io.*; class Example { public static void main(String args[]) throws IOException { FileInputStream fis = null; fis = new FileInputStream("B:/myfile.txt"); int k; while(( k = fis.read() ) != -1) { System.out.print((char)k); } fis.close(); } } Declare the exception in the method using throws keyword.
  • 17. 17 import java.io.*; class Example { public static void main(String args[]) { FileInputStream fis = null; try{ fis = new FileInputStream("B:/myfile.txt"); }catch(FileNotFoundException fnfe) { System.out.println("The specified file is not exist); } int k; try{ while(( k = fis.read() ) != -1) { System.out.print((char)k); } fis.close(); }catch(IOException ioe) { System.out.println("I/O error occurred: "+ioe); } }
  • 18. 18 Throw vs Throws in java 1. Throws clause in used to declare an exception and thow keyword is used to throw an exception explicitly. 2. If we see syntax wise than throw is followed by an instance variable and throws is followed by exception class names. 3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature). 4.By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.
  • 19. 19 User defined exception User defined exceptions in java are also known as Custom exceptions. Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions. These exceptions are known as User defined or Custom exceptions. class MyException extends Exception { String str1; MyException(String str2) { str1=str2; } public String toString() { return ("Output String = "+str1) ; } }
  • 20. 20 class CustomException { public static void main(String args[]) { try { throw new MyException("Custom"); // I'm throwing user defined custom exception above } catch(MyException exp) { System.out.println("Hi this is my catch block") ; System.out.println(exp) ; } } }
  • 21. 21 Defining Your Own Exceptions To define your own exception you must do the following: Create an exception class to hold the exception data.Your exception class must subclass "Exception" or another exception class To create unchecked exceptions, subclass the RuntimeException class. Minimally, your exception class should provide a constructor which takes the exception description as its argument. To throw your own exceptions: If your exception is checked, any method which is going to throw the exception must define it using the throws keyword When an exceptional condition occurs, create a new instance of the exception and throw it.