SlideShare a Scribd company logo
1 of 17
Exceptions in JavaExceptions in Java
javeed
What is an exception?What is an exception?
An exception is an error condition that changes
the normal flow of control in a program
Exceptions in Java separates error handling from
main business logic
Based on ideas developed in Ada, Eiffel and C++
Java has a uniform approach for handling all
synchronous errors
• From very unusual (e.g. out of memory)
• To more common ones your program should check itself
(e.g. index out of bounds)
• From Java run-time system errors (e.g., divide by zero)
• To errors that programmers detect and raise deliberately
Throwing and catchingThrowing and catching
An error can throw an exception
throw <exception object>;
By default, exceptions result in the thread
terminating after printing an error message
However, exception handlers can catch
specified exceptions and recover from error
catch (<exception type> e) {
//statements that handle the exception
}
Throwing an exceptionThrowing an exception
 Example creates a subclass of Exception and throws an
exception:
class MyException extends Exception { }
class MyClass {
void oops()
{ if (/* no error occurred */)
{ /* normal processing */ }
else { /* error occurred */
throw new MyException();
}
} //oops
}//class MyClass
Exceptional flow of controlExceptional flow of control
Exceptions break the normal flow of control.
When an exception occurs, the statement
that would normally execute next is not
executed.
What happens instead depends on:
◦ whether the exception is caught,
◦ where it is caught,
◦ what statements are executed in the ‘catch block’,
◦ and whether you have a ‘finally block’.
Approaches to handling an exceptionApproaches to handling an exception
1. Prevent the exception from happening
2. Catch it in the method in which it occurs, and
either
a. Fix up the problem and resume normal execution
b. Rethrow it
c. Throw a different exception
3. Declare that the method throws the exception
4. With 1. and 2.a. the caller never knows there
was an error.
5. With 2.b., 2.c., and 3., if the caller does not
handle the exception, the program will
terminate and display a stack trace
Exception hierarchyException hierarchy
Java organizes exceptions in inheritance
tree:
◦ Throwable
◦ Error
◦ Exception
 RuntimeException
 TooManyListenersException
 IOException
 AWTException
Java is strictJava is strict
 Unlike C++, is quite strict about catching exceptions
 If it is a checked exception
◦ (all except Error, RuntimeException and their
subclasses),
◦ Java compiler forces the caller must either catch it
◦ or explicitly re-throw it with an exception specification.
 Why is this a good idea?
 By enforcing exception specifications from top to
bottom, Java guarantees exception correctness at
compile time.
 Here’s a method that ducks out of catching an
exception by explicitly re-throwing it:
void f() throws tooBig, tooSmall, divZero {
◦ The caller of this method now must either catch these
exceptions or rethrow them in its specification.
Error and RuntimeExceptionError and RuntimeException
Error
◦ “unchecked”, thus need not be in ‘throws’ clause
◦ Serious system problems (e.g. ThreadDeath,
OutOfMemoryError)
◦ It’s very unlikely that the program will be able to recover,
so generally you should NOT catch these.
RuntimeException
◦ “unchecked”, thus need not be in ‘throws’ clause
◦ Also can occur almost anywhere, e.g.
ArithmeticException, NullPointerException,
IndexOutOfBoundsException
◦ Try to prevent them from happening in the first place!
System will print stop program and print a trace
Catching an exceptionCatching an exception
try { // statement that could throw an exception
}
catch (<exception type> e) {
// statements that handle the exception
}
catch (<exception type> e) { //e higher in hierarchy
// statements that handle the exception
}
finally {
// release resources
}
//other statements
 At most one catch block executes
 finally block always executes once, whether there’s an
error or not
Execution of try catch blocksExecution of try catch blocks
 For normal execution:
◦ try block executes, then finally block executes, then other statements
execute
 When an error is caught and the catch block throws an exception
or returns:
◦ try block is interrupted
◦ catch block executes (until throw or return statement)
◦ finally block executes
 When error is caught and catch block doesn’t throw an exception
or return:
◦ try block is interrupted
◦ catch block executes
◦ finally block executes
◦ other statements execute
 When an error occurs that is not caught:
◦ try block is interrupted
◦ finally block executes
Example:Example:
try { p.a = 10; }
catch (NullPointerException e)
{ System.out.println("p was null"); }
catch (Exception e)
{ System.out.println("other error occurred"); }
catch (Object obj)
{ System.out.println("Who threw that
object?"); }
finally { System.out.println(“final processing"); }
System.out.println(“Continue with more
statements");
Catch processingCatch processing
 When an exception occurs, the nested try/catch
statements are searched for a catch parameter matching
the exception class
 A parameter is said to match the exception if it:
◦ is the same class as the exception; or
◦ is a superclass of the exception; or
◦ if the parameter is an interface, the exception class implements
the interface.
 The first try/catch statement that has a parameter that
matches the exception has its catch statement executed.
 After the catch statement executes, execution resumes
with the finally statement, then the statements after the
try/catch statement.
Catch processing exampleCatch processing example
print("now");   
try   
{ print("is ");      
  throw new MyException();     
  print("a ");   
} 
catch(MyException e)   { print("the ");   }   
print("timen"); 
 Prints "now is the time".
 Note that exceptions don't have to be used only for error
handling
 Would it be a good idea to exceptions for non-error
processing?
 But any other use is likely to result in code that's hard to
Declaring an exception typeDeclaring an exception type
 Inherit from an existing exception type.
 Provide a default constructor
 and a constructor with one arg, type String.
 Both should call super(astring);
 Example:
class MyThrowable extends Throwable { 
// checked exception
  MyThrowable () {
     super ("Generated MyThrowable");
  }
  MyThrowable (String s) { super (s); }
}
Declaring an exception typeDeclaring an exception type
Inherit from an existing exception type.
Provide a default constructor
and a constructor with one arg, type String.
Both should call super(astring);
class ErrorThrower {
public void errorMethod() throws MyThrowable
{ throw new MyThrowable ("ErrorThrower");
// forces this method to declare MyThrowable
}
}
Exceptions are ubiquitous inExceptions are ubiquitous in
JavaJava
Exception handling required for all read
methods
◦ Also many other system methods
If you use one of Java's built in class
methods and it throws an exception, you
must catch it (i.e., surround it in a
try/catch block) or rethrow it, or you will
get a compile time error:
char ch;
try { ch = (char) System.in.read(); }
catch (IOException e)

More Related Content

What's hot (20)

Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception
ExceptionException
Exception
 
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
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception handling
Exception handlingException handling
Exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exception Handling In Java 15734
Exception Handling In Java 15734Exception Handling In Java 15734
Exception Handling In Java 15734
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 

Viewers also liked (20)

Threads
ThreadsThreads
Threads
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in java
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Java applets
Java appletsJava applets
Java applets
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
L18 applets
L18 appletsL18 applets
L18 applets
 
Java exception
Java exception Java exception
Java exception
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Java Applet
Java AppletJava Applet
Java Applet
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Java applets
Java appletsJava applets
Java applets
 
Java applets
Java appletsJava applets
Java applets
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 

Similar to exceptions in java

Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
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
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
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.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
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
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
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
 
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
 

Similar to exceptions in java (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 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
 
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
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
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
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
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
 

More from javeed_mhd

For each component in mule
For each component in muleFor each component in mule
For each component in mulejaveed_mhd
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mulejaveed_mhd
 
File component in mule
File component in muleFile component in mule
File component in mulejaveed_mhd
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mulejaveed_mhd
 
Choice component in mule
Choice component in muleChoice component in mule
Choice component in mulejaveed_mhd
 
Vm component in mule
Vm component in muleVm component in mule
Vm component in mulejaveed_mhd
 
Until successful component in mule
Until successful component in muleUntil successful component in mule
Until successful component in mulejaveed_mhd
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mulejaveed_mhd
 
Mule management console installation
Mule management console installation Mule management console installation
Mule management console installation javeed_mhd
 
Mule esb made system integration easy
Mule esb made system integration easy Mule esb made system integration easy
Mule esb made system integration easy javeed_mhd
 
Message properties component in mule
Message properties component in muleMessage properties component in mule
Message properties component in mulejaveed_mhd
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo javeed_mhd
 
How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint javeed_mhd
 
How to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudioHow to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudiojaveed_mhd
 
Mapping and listing with mule
Mapping and listing with mule Mapping and listing with mule
Mapping and listing with mule javeed_mhd
 
Mule any point exchange
Mule any point exchangeMule any point exchange
Mule any point exchangejaveed_mhd
 
Mule esb api layer
Mule esb api layer Mule esb api layer
Mule esb api layer javeed_mhd
 
Mule Maven Plugin
Mule Maven PluginMule Maven Plugin
Mule Maven Pluginjaveed_mhd
 
Mule esb stripe
Mule esb stripeMule esb stripe
Mule esb stripejaveed_mhd
 
Mule with stored procedure
Mule with stored procedureMule with stored procedure
Mule with stored procedurejaveed_mhd
 

More from javeed_mhd (20)

For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
File component in mule
File component in muleFile component in mule
File component in mule
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
 
Choice component in mule
Choice component in muleChoice component in mule
Choice component in mule
 
Vm component in mule
Vm component in muleVm component in mule
Vm component in mule
 
Until successful component in mule
Until successful component in muleUntil successful component in mule
Until successful component in mule
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mule
 
Mule management console installation
Mule management console installation Mule management console installation
Mule management console installation
 
Mule esb made system integration easy
Mule esb made system integration easy Mule esb made system integration easy
Mule esb made system integration easy
 
Message properties component in mule
Message properties component in muleMessage properties component in mule
Message properties component in mule
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
 
How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint
 
How to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudioHow to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudio
 
Mapping and listing with mule
Mapping and listing with mule Mapping and listing with mule
Mapping and listing with mule
 
Mule any point exchange
Mule any point exchangeMule any point exchange
Mule any point exchange
 
Mule esb api layer
Mule esb api layer Mule esb api layer
Mule esb api layer
 
Mule Maven Plugin
Mule Maven PluginMule Maven Plugin
Mule Maven Plugin
 
Mule esb stripe
Mule esb stripeMule esb stripe
Mule esb stripe
 
Mule with stored procedure
Mule with stored procedureMule with stored procedure
Mule with stored procedure
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

exceptions in java

  • 2. What is an exception?What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates error handling from main business logic Based on ideas developed in Ada, Eiffel and C++ Java has a uniform approach for handling all synchronous errors • From very unusual (e.g. out of memory) • To more common ones your program should check itself (e.g. index out of bounds) • From Java run-time system errors (e.g., divide by zero) • To errors that programmers detect and raise deliberately
  • 3. Throwing and catchingThrowing and catching An error can throw an exception throw <exception object>; By default, exceptions result in the thread terminating after printing an error message However, exception handlers can catch specified exceptions and recover from error catch (<exception type> e) { //statements that handle the exception }
  • 4. Throwing an exceptionThrowing an exception  Example creates a subclass of Exception and throws an exception: class MyException extends Exception { } class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ } else { /* error occurred */ throw new MyException(); } } //oops }//class MyClass
  • 5. Exceptional flow of controlExceptional flow of control Exceptions break the normal flow of control. When an exception occurs, the statement that would normally execute next is not executed. What happens instead depends on: ◦ whether the exception is caught, ◦ where it is caught, ◦ what statements are executed in the ‘catch block’, ◦ and whether you have a ‘finally block’.
  • 6. Approaches to handling an exceptionApproaches to handling an exception 1. Prevent the exception from happening 2. Catch it in the method in which it occurs, and either a. Fix up the problem and resume normal execution b. Rethrow it c. Throw a different exception 3. Declare that the method throws the exception 4. With 1. and 2.a. the caller never knows there was an error. 5. With 2.b., 2.c., and 3., if the caller does not handle the exception, the program will terminate and display a stack trace
  • 7. Exception hierarchyException hierarchy Java organizes exceptions in inheritance tree: ◦ Throwable ◦ Error ◦ Exception  RuntimeException  TooManyListenersException  IOException  AWTException
  • 8. Java is strictJava is strict  Unlike C++, is quite strict about catching exceptions  If it is a checked exception ◦ (all except Error, RuntimeException and their subclasses), ◦ Java compiler forces the caller must either catch it ◦ or explicitly re-throw it with an exception specification.  Why is this a good idea?  By enforcing exception specifications from top to bottom, Java guarantees exception correctness at compile time.  Here’s a method that ducks out of catching an exception by explicitly re-throwing it: void f() throws tooBig, tooSmall, divZero { ◦ The caller of this method now must either catch these exceptions or rethrow them in its specification.
  • 9. Error and RuntimeExceptionError and RuntimeException Error ◦ “unchecked”, thus need not be in ‘throws’ clause ◦ Serious system problems (e.g. ThreadDeath, OutOfMemoryError) ◦ It’s very unlikely that the program will be able to recover, so generally you should NOT catch these. RuntimeException ◦ “unchecked”, thus need not be in ‘throws’ clause ◦ Also can occur almost anywhere, e.g. ArithmeticException, NullPointerException, IndexOutOfBoundsException ◦ Try to prevent them from happening in the first place! System will print stop program and print a trace
  • 10. Catching an exceptionCatching an exception try { // statement that could throw an exception } catch (<exception type> e) { // statements that handle the exception } catch (<exception type> e) { //e higher in hierarchy // statements that handle the exception } finally { // release resources } //other statements  At most one catch block executes  finally block always executes once, whether there’s an error or not
  • 11. Execution of try catch blocksExecution of try catch blocks  For normal execution: ◦ try block executes, then finally block executes, then other statements execute  When an error is caught and the catch block throws an exception or returns: ◦ try block is interrupted ◦ catch block executes (until throw or return statement) ◦ finally block executes  When error is caught and catch block doesn’t throw an exception or return: ◦ try block is interrupted ◦ catch block executes ◦ finally block executes ◦ other statements execute  When an error occurs that is not caught: ◦ try block is interrupted ◦ finally block executes
  • 12. Example:Example: try { p.a = 10; } catch (NullPointerException e) { System.out.println("p was null"); } catch (Exception e) { System.out.println("other error occurred"); } catch (Object obj) { System.out.println("Who threw that object?"); } finally { System.out.println(“final processing"); } System.out.println(“Continue with more statements");
  • 13. Catch processingCatch processing  When an exception occurs, the nested try/catch statements are searched for a catch parameter matching the exception class  A parameter is said to match the exception if it: ◦ is the same class as the exception; or ◦ is a superclass of the exception; or ◦ if the parameter is an interface, the exception class implements the interface.  The first try/catch statement that has a parameter that matches the exception has its catch statement executed.  After the catch statement executes, execution resumes with the finally statement, then the statements after the try/catch statement.
  • 14. Catch processing exampleCatch processing example print("now");    try    { print("is ");         throw new MyException();        print("a ");    }  catch(MyException e)   { print("the ");   }    print("timen");   Prints "now is the time".  Note that exceptions don't have to be used only for error handling  Would it be a good idea to exceptions for non-error processing?  But any other use is likely to result in code that's hard to
  • 15. Declaring an exception typeDeclaring an exception type  Inherit from an existing exception type.  Provide a default constructor  and a constructor with one arg, type String.  Both should call super(astring);  Example: class MyThrowable extends Throwable {  // checked exception   MyThrowable () {      super ("Generated MyThrowable");   }   MyThrowable (String s) { super (s); } }
  • 16. Declaring an exception typeDeclaring an exception type Inherit from an existing exception type. Provide a default constructor and a constructor with one arg, type String. Both should call super(astring); class ErrorThrower { public void errorMethod() throws MyThrowable { throw new MyThrowable ("ErrorThrower"); // forces this method to declare MyThrowable } }
  • 17. Exceptions are ubiquitous inExceptions are ubiquitous in JavaJava Exception handling required for all read methods ◦ Also many other system methods If you use one of Java's built in class methods and it throws an exception, you must catch it (i.e., surround it in a try/catch block) or rethrow it, or you will get a compile time error: char ch; try { ch = (char) System.in.read(); } catch (IOException e)