SlideShare a Scribd company logo
1 of 23
Download to read offline
Example 3 (throwing exception)
Exercise 1
Write an application named BadScript in which you declare an array of 5
names. Write a try block in which you prompt the user for an integer and
display the name in the requested position. Create a catch block that
catches the potential ArrayIndexOutOfBoundsException thrown when
the user enters a number that is out of range. The catch block should
also display an appropriate error message.
Exercise 2
Write a program to take String input from user which contains a number
of double data-type. Extract the no. from the String to calculate its
square and display it. If the input String doesn’t contain a no. then
exception named NumberFormatException is generated at run-time,
which should be handled with an appropriate catch block. The catch
block should display the no. which caused the exception using
appropriate error message.
Keep on taking input from the user until he enters a value.
Example (re-throwing exception)
Re-throwing exception
Chained exceptions
Chained exceptions
• Sometimes, you may need to throw a new exception (with additional information) along
with the original exception. This is called chained exceptions.
Java “throws” keyword
• Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
• This is necessary for all exceptions, except those of type Error or Runtime Exception, or any of their subclasses.
• All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time
error will result.
• If method throws checked exception, then either provide try-catch block in that method or write “throws”
keyword at the method header.
• If “throws” keyword is used at the method header, then the calling method must handle the exception which
could be thrown from the called method.
Example
Java “finally” keyword
• Java finally block is a block that is used to execute important code such as closing connection, stream etc.
• “finally” creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block.
• The “finally” block will execute whether or not an exception is thrown.
• If an exception is thrown, the “finally” block will execute even if no catch statement matches the exception.
• If a “finally” block is associated with a try, the “finally” block will be executed upon conclusion of the try.
• The “finally” clause is optional. However, each try statement requires at least one catch or a “finally”
clause.
• Note: 1) For each try block there can be zero or more catch blocks, but only one finally block.
2) The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal
error that causes the process to abort).
Example
Creating Custom/user-defined Exception
Defining Custom Exceptions
• We can create our own Exception sub-classes by inheriting Exception class.
• The Exception class does not define any methods of its own.
• It inherits those methods provided by Throwable.
• Thus, all exceptions, including those that we create, have the methods defined by
Throwable available to them.
Constructors for creating Exception:
• Exception( )
• Exception(String msg)
• A custom exception class is represented by a subclass of Exception / Throwable.
• It contains the above mentioned constructor to initialize custom exception object.
Example
public class ExceptionTest
{
public static void main(String []args){
int i=Integer.parseInt(args[0]);
int j=Integer.parseInt(args[1]);
ExceptionTest t=new ExceptionTest();
try{
t.show(i); t.show(j);
}
catch(Throwable e) {
System.out.println("catched exception is "+e);
}
}
public void show(int i) throws Myexception {
if(i>100)
throw new Myexception(i);
else
System.out.println(+i+" is less then 100 it is ok");
}
}
Here object of custom class
is created and thrown
class Myexception extends Throwable
{
public Myexception(int i)
{
System.out.println("you have entered ." +i +" : It
exceeding the limit");
}
}
Custom/ user-defined
exception
Custom Exception (Example 1)
Custom Exception (Example 2)
Custom/ user-defined
exception
Assertion
Assertion
Example
If you use assertion, It will not run simply because assertion is
disabled by default. To enable the assertion, -ea or -enableassertions
switch of java must be used.
Example
One important point to understand about assertions is that you must not rely on them to
perform any action actually required by the program. The reason is that normally, released
code will be run with assertions disabled.
This statement will not
execute if assertion is not
enabled using “-ea” switch
L12.2  Exception handling.pdf

More Related Content

Similar to L12.2 Exception handling.pdf

Similar to L12.2 Exception handling.pdf (20)

Chap12
Chap12Chap12
Chap12
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Java class 7
Java class 7Java class 7
Java class 7
 
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
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
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
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Recently uploaded

Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptxanandsmhk
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsSumit Kumar yadav
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfSumit Kumar yadav
 
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...ssifa0344
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxpradhanghanshyam7136
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfSumit Kumar yadav
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptMAESTRELLAMesa2
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Boyles law module in the grade 10 science
Boyles law module in the grade 10 scienceBoyles law module in the grade 10 science
Boyles law module in the grade 10 sciencefloriejanemacaya1
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Patrick Diehl
 

Recently uploaded (20)

Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questions
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdf
 
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptx
 
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdf
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.ppt
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Boyles law module in the grade 10 science
Boyles law module in the grade 10 scienceBoyles law module in the grade 10 science
Boyles law module in the grade 10 science
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?
 

L12.2 Exception handling.pdf

  • 1. Example 3 (throwing exception)
  • 2. Exercise 1 Write an application named BadScript in which you declare an array of 5 names. Write a try block in which you prompt the user for an integer and display the name in the requested position. Create a catch block that catches the potential ArrayIndexOutOfBoundsException thrown when the user enters a number that is out of range. The catch block should also display an appropriate error message.
  • 3. Exercise 2 Write a program to take String input from user which contains a number of double data-type. Extract the no. from the String to calculate its square and display it. If the input String doesn’t contain a no. then exception named NumberFormatException is generated at run-time, which should be handled with an appropriate catch block. The catch block should display the no. which caused the exception using appropriate error message. Keep on taking input from the user until he enters a value.
  • 6. Chained exceptions • Sometimes, you may need to throw a new exception (with additional information) along with the original exception. This is called chained exceptions.
  • 7. Java “throws” keyword • Syntax: type method-name(parameter-list) throws exception-list { // body of method } • This is necessary for all exceptions, except those of type Error or Runtime Exception, or any of their subclasses. • All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
  • 8. • If method throws checked exception, then either provide try-catch block in that method or write “throws” keyword at the method header. • If “throws” keyword is used at the method header, then the calling method must handle the exception which could be thrown from the called method.
  • 10. Java “finally” keyword • Java finally block is a block that is used to execute important code such as closing connection, stream etc. • “finally” creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. • The “finally” block will execute whether or not an exception is thrown. • If an exception is thrown, the “finally” block will execute even if no catch statement matches the exception. • If a “finally” block is associated with a try, the “finally” block will be executed upon conclusion of the try. • The “finally” clause is optional. However, each try statement requires at least one catch or a “finally” clause. • Note: 1) For each try block there can be zero or more catch blocks, but only one finally block. 2) The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
  • 13. Defining Custom Exceptions • We can create our own Exception sub-classes by inheriting Exception class. • The Exception class does not define any methods of its own. • It inherits those methods provided by Throwable. • Thus, all exceptions, including those that we create, have the methods defined by Throwable available to them.
  • 14. Constructors for creating Exception: • Exception( ) • Exception(String msg) • A custom exception class is represented by a subclass of Exception / Throwable. • It contains the above mentioned constructor to initialize custom exception object.
  • 15. Example public class ExceptionTest { public static void main(String []args){ int i=Integer.parseInt(args[0]); int j=Integer.parseInt(args[1]); ExceptionTest t=new ExceptionTest(); try{ t.show(i); t.show(j); } catch(Throwable e) { System.out.println("catched exception is "+e); } } public void show(int i) throws Myexception { if(i>100) throw new Myexception(i); else System.out.println(+i+" is less then 100 it is ok"); } } Here object of custom class is created and thrown class Myexception extends Throwable { public Myexception(int i) { System.out.println("you have entered ." +i +" : It exceeding the limit"); } }
  • 17. Custom Exception (Example 2) Custom/ user-defined exception
  • 20. Example If you use assertion, It will not run simply because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used.
  • 22. One important point to understand about assertions is that you must not rely on them to perform any action actually required by the program. The reason is that normally, released code will be run with assertions disabled. This statement will not execute if assertion is not enabled using “-ea” switch