SlideShare a Scribd company logo
Unit - III
Exception Handling and Multithreading
What is Exception in Java?
 Exceptions are events that occur during the execution of programs that disrupt the
normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).
 Exception is an object which is thrown at runtime.
 Exception objects can be thrown and caught.
What is Exception Handling?
 Exception Handling is a mechanism to handle runtime errors such as
 ClassNotFoundException,
 IOException,
 SQLException,
 RemoteException, etc.
Advantage of Exception Handling
 The advantage of exception handling is to maintain the normal flow of the
application.
 An exception normally disrupts the normal flow of the application; that is why we
need to handle exceptions.
 Example:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
 Suppose there are 10 statements in a Java program and an exception occurs at
statement 5;
 The rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed.
 However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
 The java.lang.Throwable class is the root class of Java Exception.
 The hierarchy inherited by two subclasses:
 Exception and
 Error
Exceptions are used to indicate many different types of error conditions.
 JVM Errors:
 OutOfMemoryError
 StackOverflowError
 LinkageError
 System errors:
 FileNotFoundException
 IOException
 SocketTimeoutException
 Programming errors:
 NullPointerException
 ArrayIndexOutOfBoundsException
 ArithmeticException
Types of Exceptions
 Java defines several types of exceptions that relate to its various class libraries.
 Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions
 Built-in exceptions are the exceptions that are available in Java libraries.
 These exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The compiler will not check these exceptions at compile
time. In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error.
2. User-Defined Exceptions:
 Users can also create exceptions, which are called ‘user-defined Exceptions’.
Advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Common Scenarios of Java Exceptions
 There are given some scenarios where unchecked exceptions may occur. They are
as follows:
1) A scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
2) A scenario where NullPointerException occurs
 If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) A scenario where NumberFormatException occurs
 If the formatting of any variable or number is mismatched, it may result into
NumberFormatException.
 Suppose we have a string variable that has characters; converting this variable into
digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
 When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
 There may be other reasons to occur ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Keywords
 Java provides five keywords that are used to handle the exception.
Keyword Description
Try  The "try" keyword is used to specify a block where we
should place an exception code.
 It means we can't use try block alone.
 The try block must be followed by either catch or finally.
Catch  The "catch" block is used to handle the exception.
 It must be preceded by try block which means we can't use
catch block alone.
Finally  The "finally" block is used to execute the necessary code of
the program.
 It is executed whether an exception is handled or not.
Throw  The "throw" keyword is used to throw an exception.
Throws  The "throws" keyword is used to declare exceptions.
 It specifies that there may occur an exception in the method.
 It doesn't throw an exception.
 It is always used with method signature.
Java try and catch
 The try statement allows you to define a block of code to be tested for errors while
it is being executed.
 The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Java try block:
 Java try block is used to enclose the code that might throw an exception.
 It must be used within the method.
 If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute.
 So, it is recommended not to keep the code in try block that will not throw an
exception.
 Java try block must be followed by either catch or finally block.
Syntax of Java try-catch:
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Syntax of try-finally block:
Try
{
//code that may throw an exception
}
Finally
{
}
Java catch block
 Java catch block is used to handle the Exception by declaring the type of exception
within the parameter.
 The declared exception must be the parent class exception ( i.e., Exception)
 The catch block must be used after the try block only.
 You can use multiple catch block with a single try block.
Internal Working of Java try-catch block:
 The JVM firstly checks whether the exception is handled or not.
 If exception is not handled, JVM provides a default exception handler that performs
the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
 But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Example1: Problem without exception handling
 if we don't use a try-catch block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 2: Solution by exception handling
 Using java try-catch block.
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3: In this example, we also kept the code in a try block that will not throw
an exception.
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will
not execute.
Example 4: Here, we handle the exception using the parent class exception.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5: to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output: Can't divided by zero
Example 6: to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Java Multi-catch block:
 A try block can be followed by one or more catch blocks.
 Each catch block must contain a different exception handler.
 At a time only one exception occurs and at a time only one catch block is
executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch
for ArithmeticException must come before catch for Exception.
Example: java multi-catch block.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
OUTPUT
Arithmetic Exception occurs
rest of the code
Java Nested try block:
 In Java, using a try block inside another try block is permitted. It is called as nested
try block.
 For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example: a try block within another try block for two different exceptions.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
Java throw keyword
 The Java throw keyword is used to throw an exception explicitly.
 We can define our own set of conditions and throw an exception explicitly using
throw keyword.
 For example, we can throw ArithmeticException if we divide a number by another
number.
 Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Example of throw IOException.
throw new IOException("sorry device error");
Java throw keyword Example
Example 1: Throwing Unchecked Exception
 In this example, we have created a method named validate() that accepts an integer
as a parameter.
 If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Example 2: Throwing Checked Exception
Every subclass of Error and RuntimeException is an unchecked exception in java. A
checked exception is everything else under the Throwable class.
import java.io.*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
Example:
Case 1: When an exception does not occur
 Java program does not throw any exception, and the finally block is executed after
the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
Case 2: When an exception occur but not handled by the catch block
 Here, the code throws an exception however the catch block cannot handle it.
 Despite this, the finally block is executed after the try block and then the program
terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
Lab Program7:Write a java program to implement Exception Handling
import java.io.*;
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail=a;
}
public String toString()
{
return "Minor with age less than 18 and you are only "+detail;
}
}
class ExceptionDemo
{
static void compute(int x)throws MyException
{
if(x<18)
throw new MyException(x);
else
System.out.println("You can voten");
}
public static void main(String arg[])
{
try
{
compute(20);
compute(15);
}
catch(MyException e)
{
System.out.println("My Exception caught "+e);
}
finally
{
System.out.println("nYou are an Indian");
} } }

More Related Content

Similar to Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch.

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
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
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
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
Kuntal Bhowmick
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
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
HayomeTakele
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
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
Kuntal Bhowmick
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
Swabhav Techlabs
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 

Similar to Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch. (20)

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
 
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
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
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
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
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
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
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 in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

Recently uploaded

在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
2zjra9bn
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
Bruce Bennett
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
Thomas GIRARD BDes
 
lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789
Ghh
 
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employeesLeave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Sreenivas702647
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
kakomaeric00
 
5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf
Alliance Jobs
 
IT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a RoadmapIT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a Roadmap
Base Camp
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
dsnow9802
 
Learnings from Successful Jobs Searchers
Learnings from Successful Jobs SearchersLearnings from Successful Jobs Searchers
Learnings from Successful Jobs Searchers
Bruce Bennett
 
Introducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptxIntroducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptx
FauzanHarits1
 
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdfSwitching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
SocMediaFin - Joyce Sullivan
 
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAANBUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
cahgading001
 
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
NWEXAM
 
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
MuhammadWaqasBaloch1
 
Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024
SnapJob
 
thyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatialthyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatial
Aditya Raghav
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
Bruce Bennett
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
2zjra9bn
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
taqyea
 

Recently uploaded (20)

在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
 
lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789
 
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employeesLeave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employees
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
 
5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf
 
IT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a RoadmapIT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a Roadmap
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
 
Learnings from Successful Jobs Searchers
Learnings from Successful Jobs SearchersLearnings from Successful Jobs Searchers
Learnings from Successful Jobs Searchers
 
Introducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptxIntroducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptx
 
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdfSwitching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
 
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAANBUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
 
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
 
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
 
Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024
 
thyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatialthyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatial
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
 

Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch.

  • 1. Unit - III Exception Handling and Multithreading What is Exception in Java?  Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).  Exception is an object which is thrown at runtime.  Exception objects can be thrown and caught. What is Exception Handling?  Exception Handling is a mechanism to handle runtime errors such as  ClassNotFoundException,  IOException,  SQLException,  RemoteException, etc. Advantage of Exception Handling  The advantage of exception handling is to maintain the normal flow of the application.  An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
  • 2.  Example: statement 1; statement 2; statement 3; statement 4; statement 5;//exception occurs statement 6; statement 7; statement 8; statement 9; statement 10;  Suppose there are 10 statements in a Java program and an exception occurs at statement 5;  The rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.  However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java. Hierarchy of Java Exception classes  The java.lang.Throwable class is the root class of Java Exception.  The hierarchy inherited by two subclasses:  Exception and  Error
  • 3. Exceptions are used to indicate many different types of error conditions.  JVM Errors:  OutOfMemoryError  StackOverflowError  LinkageError  System errors:  FileNotFoundException  IOException
  • 4.  SocketTimeoutException  Programming errors:  NullPointerException  ArrayIndexOutOfBoundsException  ArithmeticException Types of Exceptions  Java defines several types of exceptions that relate to its various class libraries.  Java also allows users to define their own exceptions. Exceptions can be categorized in two ways: 1. Built-in Exceptions  Checked Exception  Unchecked Exception 2. User-Defined Exceptions 1. Built-in Exceptions  Built-in exceptions are the exceptions that are available in Java libraries.
  • 5.  These exceptions are suitable to explain certain error situations. Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. Unchecked Exceptions: The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error. 2. User-Defined Exceptions:  Users can also create exceptions, which are called ‘user-defined Exceptions’. Advantages of Exception Handling in Java are as follows: 1. Provision to Complete Program Execution 2. Easy Identification of Program Code and Error-Handling Code 3. Propagation of Errors 4. Meaningful Error Reporting 5. Identifying Error Types Common Scenarios of Java Exceptions  There are given some scenarios where unchecked exceptions may occur. They are as follows: 1) A scenario where ArithmeticException occurs  If we divide any number by zero, there occurs an ArithmeticException. int a=50/0; //ArithmeticException 2) A scenario where NullPointerException occurs  If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
  • 6. String s=null; System.out.println(s.length()); //NullPointerException 3) A scenario where NumberFormatException occurs  If the formatting of any variable or number is mismatched, it may result into NumberFormatException.  Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) A scenario where ArrayIndexOutOfBoundsException occurs  When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.  There may be other reasons to occur ArrayIndexOutOfBoundsException. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 7. Java Exception Keywords  Java provides five keywords that are used to handle the exception. Keyword Description Try  The "try" keyword is used to specify a block where we should place an exception code.  It means we can't use try block alone.  The try block must be followed by either catch or finally. Catch  The "catch" block is used to handle the exception.  It must be preceded by try block which means we can't use catch block alone. Finally  The "finally" block is used to execute the necessary code of the program.  It is executed whether an exception is handled or not. Throw  The "throw" keyword is used to throw an exception. Throws  The "throws" keyword is used to declare exceptions.  It specifies that there may occur an exception in the method.  It doesn't throw an exception.  It is always used with method signature.
  • 8. Java try and catch  The try statement allows you to define a block of code to be tested for errors while it is being executed.  The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. Java try block:  Java try block is used to enclose the code that might throw an exception.  It must be used within the method.  If an exception occurs at the particular statement in the try block, the rest of the block code will not execute.  So, it is recommended not to keep the code in try block that will not throw an exception.  Java try block must be followed by either catch or finally block. Syntax of Java try-catch: try { //code that may throw an exception } catch(Exception_class_Name ref) { } Syntax of try-finally block: Try { //code that may throw an exception } Finally { }
  • 9. Java catch block  Java catch block is used to handle the Exception by declaring the type of exception within the parameter.  The declared exception must be the parent class exception ( i.e., Exception)  The catch block must be used after the try block only.  You can use multiple catch block with a single try block. Internal Working of Java try-catch block:  The JVM firstly checks whether the exception is handled or not.  If exception is not handled, JVM provides a default exception handler that performs the following tasks:  Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).  Causes the program to terminate.
  • 10.  But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed. Example1: Problem without exception handling  if we don't use a try-catch block. public class TryCatchExample1 { public static void main(String[] args) { int data=50/0; //may throw exception System.out.println("rest of the code"); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero Example 2: Solution by exception handling  Using java try-catch block. public class TryCatchExample2 { public static void main(String[] args) { try { int data=50/0; //may throw exception } //handling the exception catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code");
  • 11. } } Output: java.lang.ArithmeticException: / by zero rest of the code Example 3: In this example, we also kept the code in a try block that will not throw an exception. public class TryCatchExample3 { public static void main(String[] args) { try { int data=50/0; //may throw exception // if exception occurs, the remaining statement will not exceute System.out.println("rest of the code"); } // handling the exception catch(ArithmeticException e) { System.out.println(e); } } } Output: java.lang.ArithmeticException: / by zero Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
  • 12. Example 4: Here, we handle the exception using the parent class exception. public class TryCatchExample4 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception by using Exception class catch(Exception e) { System.out.println(e); } System.out.println("rest of the code"); } } Output: java.lang.ArithmeticException: / by zero rest of the code Example 5: to print a custom message on exception. public class TryCatchExample5 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception catch(Exception e)
  • 13. { // displaying the custom message System.out.println("Can't divided by zero"); } } } Output: Can't divided by zero Example 6: to resolve the exception in a catch block. public class TryCatchExample6 { public static void main(String[] args) { int i=50; int j=0; int data; try { data=i/j; //may throw exception } // handling the exception catch(Exception e) { // resolving the exception in catch block System.out.println(i/(j+2)); } } } Output: 25
  • 14. Java Multi-catch block:  A try block can be followed by one or more catch blocks.  Each catch block must contain a different exception handler.  At a time only one exception occurs and at a time only one catch block is executed.  All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 15. Example: java multi-catch block. public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } } OUTPUT Arithmetic Exception occurs rest of the code Java Nested try block:  In Java, using a try block inside another try block is permitted. It is called as nested try block.  For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
  • 16. Syntax: .... //main try block try { statement 1; statement 2; //try catch block within another try block try { statement 3; statement 4; //try catch block within nested try block try { statement 5; statement 6; } catch(Exception e2) { //exception message } } catch(Exception e1) { //exception message } } //catch block of parent (outer) try block catch(Exception e3) { //exception message
  • 17. } .... Example: a try block within another try block for two different exceptions. public class NestedTryBlock{ public static void main(String args[]){ //outer try block try{ //inner try block 1 try{ System.out.println("going to divide by 0"); int b =39/0; } //catch block of inner try block 1 catch(ArithmeticException e) { System.out.println(e); } //inner try block 2 try{ int a[]=new int[5]; //assigning the value out of array bounds a[5]=4; } //catch block of inner try block 2 catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); } //catch block of outer try block catch(Exception e) { System.out.println("handled the exception (outer catch)");
  • 18. } System.out.println("normal flow.."); } } Output: Java throw keyword  The Java throw keyword is used to throw an exception explicitly.  We can define our own set of conditions and throw an exception explicitly using throw keyword.  For example, we can throw ArithmeticException if we divide a number by another number.  Here, we just need to set the condition and throw exception using throw keyword. The syntax of the Java throw keyword is given below. throw Instance i.e., throw new exception_class("error message"); Example of throw IOException. throw new IOException("sorry device error"); Java throw keyword Example Example 1: Throwing Unchecked Exception  In this example, we have created a method named validate() that accepts an integer as a parameter.
  • 19.  If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } //main method public static void main(String args[]){ //calling the function validate(13); System.out.println("rest of the code..."); } } Example 2: Throwing Checked Exception Every subclass of Error and RuntimeException is an unchecked exception in java. A checked exception is everything else under the Throwable class. import java.io.*; public class TestThrow2 {
  • 20. //function to check if person is eligible to vote or not public static void method() throws FileNotFoundException { FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt"); BufferedReader fileInput = new BufferedReader(file); throw new FileNotFoundException(); } //main method public static void main(String args[]){ try { method(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("rest of the code..."); } } Output:
  • 21. Example 3: Throwing User-defined Exception exception is everything else under the Throwable class. TestThrow3.java // class represents user-defined exception class UserDefinedException extends Exception { public UserDefinedException(String str) { // Calling constructor of parent Exception super(str); } } // Class that uses above MyException public class TestThrow3 { public static void main(String args[]) { try { // throw an object of user defined exception throw new UserDefinedException("This is user-defined exception"); } catch (UserDefinedException ude) { System.out.println("Caught the exception"); // Print the message from MyException object System.out.println(ude.getMessage()); } } } Output:
  • 22. Java finally block Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.
  • 23. Example: Case 1: When an exception does not occur  Java program does not throw any exception, and the finally block is executed after the try block. class TestFinallyBlock { public static void main(String args[]){ try{ //below code do not throw any exception int data=25/5; System.out.println(data); } //catch won't be executed catch(NullPointerException e){ System.out.println(e); } //executed regardless of exception occurred or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } OUTPUT Case 2: When an exception occur but not handled by the catch block  Here, the code throws an exception however the catch block cannot handle it.
  • 24.  Despite this, the finally block is executed after the try block and then the program terminates abnormally. public class TestFinallyBlock1{ public static void main(String args[]){ try { System.out.println("Inside the try block"); //below code throws divide by zero exception int data=25/0; System.out.println(data); } //cannot handle Arithmetic type exception //can only accept Null Pointer type exception catch(NullPointerException e){ System.out.println(e); } //executes regardless of exception occured or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Output:
  • 25. Lab Program7:Write a java program to implement Exception Handling import java.io.*; class MyException extends Exception { private int detail; MyException(int a) { detail=a; } public String toString() { return "Minor with age less than 18 and you are only "+detail; } } class ExceptionDemo { static void compute(int x)throws MyException { if(x<18) throw new MyException(x); else System.out.println("You can voten"); } public static void main(String arg[]) { try { compute(20); compute(15); } catch(MyException e) { System.out.println("My Exception caught "+e); } finally { System.out.println("nYou are an Indian"); } } }