SlideShare a Scribd company logo
1 of 24
Here, i will discuss what is an
exception and how it can be
handled in java programming
language.
An Exception can be anything which interrupts the normal
flow of the program. When an exception occurs program
processing gets terminated and doesn’t continue further.
In such cases we get a system generated error message. In
other words, an exception is a run-time error. The good
thing about exceptions is that they can be handled.
What is an exception?
Exception can occur at runtime (known as runtime exceptions) as
well as at compile-time (known Compile-time exceptions).
In example-
 Dividing a number by zero.
 Accessing an element that is out of bounds of an array.
 Trying to store incompatible data elements.
 Trying to convert from string to specific data value.
 File errors: not found, permissions error etc.
 Corrupting memory.
 Network connection error.
When an exception can occur?
 Exception handling allows us to control the normal flow of
the program by using exception handling in program.
 It throws an exception whenever a calling method
encounters an error providing that the calling method
takes care of that error.
 It also gives us the scope of organizing and differentiating
between different error types using a separate block of
codes. This is done with the help of try-catch blocks.
Advantages of Exception Handling
If an exception is raised, which has not been handled by programmer
then program execution can get terminated and system prints a non
user friendly error message.
We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the
time exception occurs due to bad data provided by user.
Why to handle exception?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
In computer languages that do not support exception
handling, errors must be checked and handled manually—
typically through the use of error codes, and so on. This
approach is as cumbersome as it is troublesome. Java’s
exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented
world.
Exception Handling in Java
 ArithmeticException
 ArrayIndexOutOfBoundsExcep
tion
 NullPointerException
 NegativeArraySizeException
Unchecked exceptions
 ClassNotFoundException
 IllegalAccessException
 NoSuchFieldException
 EOFException
Checked exceptions
Types of exceptions in Java
1) try
2) catch
3) throw
4) throws
5) finally
Java Exception Handling Keywords
try {
// block of code to monitor for errors
// throw exception explicitly (mainly custom exception)
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
General Form of an Exception Handling Block
Java try block is used to enclose the code that might throw
an exception. It must be used within the method.
Possible forms of try statement:
1. try-catch
2. try-finally
3. try-catch-finally
If an exception occurs in a try statement, execution of the try
statement is terminated. A catch statement handles the
exeception thrown by the try statement.
Java try Block
Java catch block is used to handle the Exception. It must be
used after the try block only. If you have to perform
different tasks at the occurrence of different Exceptions,
use java multi catch block with a single try.
Rules for multiple catch block:
1. At a time only one Exception is occured and at a time only
one catch block is executed.
2. All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must
come before catch for Exception .
Java catch Block
Internal
working
of java
try-catch
block
Task1 is completed
rest of the code…
public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) {
System.out.println("common task completed"); }
System.out.println("rest of the code...");
}
}
Java finally block is a block that is used to execute
important code such as closing connection, stream etc. It is
always executed whether exception is handled or not. It
can be used to put "cleanup" code such as closing a file,
closing connection etc.
Rules for finally block:
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).
Java finally Block
Internal
working
of java
try-catch-
finally
block
Task1 is completed
finally block is always executed
rest of the code…
public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) { System.out.println("common task completed"); }
finally { System.out.println(“finally block is always executed”); }
System.out.println("rest of the code...");
}
}
The Java throw keyword is used to explicitly throw an
exception mainly custom exception. We can throw either
checked or uncheked exception in java by throw keyword.
Syntax:
throw exception;
// throw custom exception
throw new IOException("sorry device error);
// throw IOException
Java throw Keyword
Exception in thread main java.lang.ArithmeticException:not valid
public class TestThrow1{
static void validate(int age) {
if(age<18) throw new ArithmeticException("not valid");
else System.out.println("welcome to vote");
}
public static void main(String args[]) {
validate(13);
System.out.println("rest of the code...");
}
}
The Java throws keyword is used to declare an exception. It
gives an information to the programmer that there may
occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can
be maintained.
Syntax:
return_type method_name() throws exception_class_name {
// method code
}
Java throws Keyword
No throw throws
1 Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to declare
an exception.
2 Checked exception cannot be
propagated using throw only.
Checked exception can be propagated
with throws.
3 Throw is followed by an instance. Throws is followed by class.
4 Throw is used within the method. Throws is used with the method
signature.
5 You cannot throw multiple
exceptions.
You can declare multiple exceptions e.g.
public void method() throws
IOException,SQLException
Difference between throw and throws in Java
Md. Arafat Islam
Roll: 150126
Department of Computer Science and Engineering
Pabna University of Science and Technology
ThankYou

More Related Content

What's hot

What's hot (20)

Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Creating your own exception
Creating your own exceptionCreating your own exception
Creating your own exception
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 

Similar to Exception handling in java

Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming languageushakiranv110
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingGovindanS3
 
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
 

Similar to Exception handling in java (20)

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
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
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 Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
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
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
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
 
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
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handling
Exception handlingException handling
Exception handling
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Exception handling in java

  • 1.
  • 2. Here, i will discuss what is an exception and how it can be handled in java programming language.
  • 3. An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message. In other words, an exception is a run-time error. The good thing about exceptions is that they can be handled. What is an exception?
  • 4. Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions). In example-  Dividing a number by zero.  Accessing an element that is out of bounds of an array.  Trying to store incompatible data elements.  Trying to convert from string to specific data value.  File errors: not found, permissions error etc.  Corrupting memory.  Network connection error. When an exception can occur?
  • 5.  Exception handling allows us to control the normal flow of the program by using exception handling in program.  It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.  It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. Advantages of Exception Handling
  • 6. If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user. Why to handle exception? Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5) ExceptionDemo : The class name main : The method name ExceptionDemo.java : The filename java:5 : Line number
  • 7. In computer languages that do not support exception handling, errors must be checked and handled manually— typically through the use of error codes, and so on. This approach is as cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process, brings run-time error management into the object oriented world. Exception Handling in Java
  • 8.  ArithmeticException  ArrayIndexOutOfBoundsExcep tion  NullPointerException  NegativeArraySizeException Unchecked exceptions  ClassNotFoundException  IllegalAccessException  NoSuchFieldException  EOFException Checked exceptions Types of exceptions in Java
  • 9.
  • 10. 1) try 2) catch 3) throw 4) throws 5) finally Java Exception Handling Keywords
  • 11. try { // block of code to monitor for errors // throw exception explicitly (mainly custom exception) } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends } General Form of an Exception Handling Block
  • 12. Java try block is used to enclose the code that might throw an exception. It must be used within the method. Possible forms of try statement: 1. try-catch 2. try-finally 3. try-catch-finally If an exception occurs in a try statement, execution of the try statement is terminated. A catch statement handles the exeception thrown by the try statement. Java try Block
  • 13. Java catch block is used to handle the Exception. It must be used after the try block only. If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block with a single try. Rules for multiple catch block: 1. At a time only one Exception is occured and at a time only one catch block is executed. 2. All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception . Java catch Block
  • 15. Task1 is completed rest of the code… public class TestMultipleCatchBlock { public static void main (String args[]) { try { int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed"); } catch(Exception e) { System.out.println("common task completed"); } System.out.println("rest of the code..."); } }
  • 16. Java finally block is a block that is used to execute important code such as closing connection, stream etc. It is always executed whether exception is handled or not. It can be used to put "cleanup" code such as closing a file, closing connection etc. Rules for finally block: 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). Java finally Block
  • 18. Task1 is completed finally block is always executed rest of the code… public class TestMultipleCatchBlock { public static void main (String args[]) { try { int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed"); } catch(Exception e) { System.out.println("common task completed"); } finally { System.out.println(“finally block is always executed”); } System.out.println("rest of the code..."); } }
  • 19. The Java throw keyword is used to explicitly throw an exception mainly custom exception. We can throw either checked or uncheked exception in java by throw keyword. Syntax: throw exception; // throw custom exception throw new IOException("sorry device error); // throw IOException Java throw Keyword
  • 20. Exception in thread main java.lang.ArithmeticException:not valid public class TestThrow1{ static void validate(int age) { if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]) { validate(13); System.out.println("rest of the code..."); } }
  • 21. The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Syntax: return_type method_name() throws exception_class_name { // method code } Java throws Keyword
  • 22. No throw throws 1 Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2 Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws. 3 Throw is followed by an instance. Throws is followed by class. 4 Throw is used within the method. Throws is used with the method signature. 5 You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method() throws IOException,SQLException Difference between throw and throws in Java
  • 23. Md. Arafat Islam Roll: 150126 Department of Computer Science and Engineering Pabna University of Science and Technology