SlideShare a Scribd company logo
Exception Handling
What is Exception?
Exception Handling
An exception can occur for following
reasons.
•User error
•Programmer error
•Physical error
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
int x=10;
int y=0;
int z=x/y;
System.out.println(z);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Exception in thread "main" java.lang.ArithmeticException: / by zero at
MyClass.main(MyClass.java:6)
Output
import java.io.*;
public class Main {
public static void main(String[] args){
System.out.println("First line");
System.out.println("Second line");
int[] myIntArray = new int[]{1, 2, 3};
print(myIntArray);
System.out.println("Third line");
}
public static void print(int[] arr) {
System.out.println(arr[3]);
System.out.println("Fourth element successfully displayed!");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
First line
Second line
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.print(Main.java:11)
at Main.main(Main.java:7)
Output
Throwable
Error
Exception IOException
SQLException
ClassNot
FoundException
RuntimeException
Hierarchy of Java Exception classes
Types of Exception
•Checked Exception
•Unchecked Exception
//Example for Checked exception
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
fis = new FileInputStream(“D:/myfile.txt");
int k;
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Output
//Example for Unchecked exception
import java.io.*;
public class Main {
public static void main(String[] args){
int[] arr = new int[]{7, 11, 30, 63};
System.out.println(arr[5]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:5)
Output
Exception Handling
Exception Handling?
It is the process of responding to the
occurrence during computation of
exceptions.
Exceptional Handling Keywords
•try
•catch
•finally
•throw
•throws
import java.util.*;
public class MyClass
{
public static void main(String
args[])
{
int x=10;
int y=0;
int z=x/y;
System.out.println(z);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class MyClass
{
public static void main(String
args[])
{
int x=10;
int y=0;
try
{
int z=x/y;
}
catch(Exception e)
{
System.out.print(e);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class MyClass
{
public static void main(String
args[])
{
int x=10;
int y=0;
try
{
int z=x/y;
}
catch(Exception e)
{
System.out.print(e);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Output:
java.lang.ArithmeticException: /
by zero
Syntax:
try
{
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
comment/pseudo code/output
import java.io.*;
public class Main {
public static void main(String[] args){
System.out.println("First line");
System.out.println("Second line");
try{
int[] myIntArray = new int[]{1, 2, 3};
print(myIntArray);
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("The array doesn't have fourth element!");
}
System.out.println("Third line");
}
public static void print(int[] arr) {
System.out.println(arr[3]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
First line
Second line
The array doesn't have fourth element!
Third line
OUTPUT
System.out.print(arr[3])
Internal Working of try-catch Block
An object of
exception class is
thrown
JVM
• Prints out exception
Description
• Prints stack trace
• Terminates the
program
rest of code
is executed
yes
Exception object
Is
Handled?
no
rest of code
is executed
yes
Exception object
Is
Handled?
no
//Predict the Output
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
MyClass ob = new MyClass();
try
{
ob.meth1();
}
catch(ArithmeticException e)
{
System.out.println("ArithmaticException thrown by meth1()
method is caught in main() method");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void meth1()
{
try
{
System.out.println(100/0);
}
catch(NullPointerException nullExp)
{
System.out.println("We have an Exception - "+nullExp);
}
System.out.println("Outside try-catch block");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class MyClass {
public static void main(String[] args) {
try{
int arr[]=new int[5];
arr[7]=100/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");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Predict the Output
import java.util.*;
public class MyClass
{
public static void main(String[] args)
{
String[] s = {"Hello", "423", null, "Hi"};
for (int i = 0; i < 5; i++)
{
try
{
int a = s[i].length() + Integer.parseInt(s[i]);
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
catch (ArrayIndexOutOfBoundsException ex)
{
System.out.println("ArrayIndexOutOfBoundsException");
}
catch (NullPointerException ex)
{
System.out.println("NullPointerException");
}
System.out.println("After catch, this statement will be
executed");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Pipe(|) operator
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String[] s = {"abc", "123", null, "xyz"};
for (int i = 0; i < 5; i++)
{
try
{
int a = s[i].length() + Integer.parseInt(s[i]);
}
catch(NumberFormatException | NullPointerException |
ArrayIndexOutOfBoundsException ex)
{
System.out.println("Handles above mentioned three
Exception");
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Predict the output
import java.util.*;
public class Main
{
public static void main(String[] args)
{
try
{
int i = Integer.parseInt("Thor");
}
catch(Exception ex)
{
System.out.println("This block handles all exception types");
}
catch(NumberFormatException ex)
{
System.out.print("This block handles NumberFormatException");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Predict the OUtput
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String[] str = {null, "Marvel"};
for (int i = 0; i < str.length; i++)
{
try
{
int a = str[i].length();
try
{
a = Integer.parseInt(str[i]);
}
catch (NumberFormatException ex)
{
System.out.println("NumberFormatException");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
catch(NullPointerException ex)
{
System.out.println("NullPointerException");
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Syntax for finally block
try {
//Statements that may cause an
exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
It contains all the crucial
statements that must be executed
whether exception occurs or not.
Description
public class MyClass{
public static void main(String args[]){
try{
int data = 30/3;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyClass
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyClass
{
public static void main(String args[])
{
System.out.println(MyClass.myMethod());
}
public static int myMethod()
{
try
{
return 0;
}
finally
{
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return
statement");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyClass
{
public static void main(String args[])
{
System.out.println(MyClass.myMethod());
}
public static int myMethod()
{
try
{
return 0;
}
finally
{
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return
statement");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Cases when the finally block doesn’t
execute
• The death of a Thread.
• Using of the System. exit() method.
• Due to an exception arising in the finally block.
public class MyClass{
public static void main(String args[])
{
System.out.println(MyClass.myMethod());
}
public static int myMethod(){
try {
int x = 63;
int y = 9;
int z=x/y;
System.out.println("Inside try block");
System.exit(0);
}
catch (Exception exp){
System.out.println(exp);
}
finally{
System.out.println("Java finally block");
return 0;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyClass{
public static void main(String args[])
{
System.out.println(MyClass.myMethod());
}
public static int myMethod(){
try {
int x = 63;
int y = 0;
int z=x/y;
System.out.println("Inside try block");
System.exit(0);
}
catch (Exception exp){
System.out.println(exp);
}
finally{
System.out.println("Java finally block");
return 0;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Syntax for throw block
throw new exception_class("error message");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
The Java throw keyword is used
to explicitly throw an
exception.
Description
public class MyClass
{
public static void validate(int age)
{
if(age<21 || age>27)
throw new ArithmeticException("not eligible");
else
System.out.println("Eligible to attend Military Selection ");
}
public static void main(String args[])
{
validate(30);
System.out.println("rest of the code...");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Exception in thread "main" java.lang.ArithmeticException: not eligible
at MyClass.validate(MyClass.java:6)
at MyClass.main(MyClass.java:12)
OUTPUT
public class MyClass
{
public static void validate(int age)
{
if(age<21 || age>27)
throw new ArithmeticException("not eligible");
else
System.out.println("Eligible to attend Military Selection ");
}
public static void main(String args[])
{
try
{
validate(30);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
java.lang.ArithmeticException: not eligible
rest of the code...
OUTPUT
public class MyClass
{
public static void validate(int age)
{
if(age<21 || age>27)
throw new ArithmeticException("not eligible");
else
System.out.println("Eligible to attend Military Selection ");
}
public static void main(String args[])
{
try
{
validate(21);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Eligible to attend Military Selection
rest of the code...
OUTPUT
THANK YOU

More Related Content

Similar to STS4022 Exceptional_Handling

Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
mayorothenguyenhob69
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
dhrubo kayal
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
Fraz Bakhsh
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdfJava_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf
JayveeCultivo
 
Lab4
Lab4Lab4
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Exception handling
Exception handlingException handling
Exception handling
Kapish Joshi
 
14 thread
14 thread14 thread
14 thread
Bayarkhuu
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
cbeproject centercoimbatore
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
MaruMengesha
 

Similar to STS4022 Exceptional_Handling (20)

Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
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 Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdfJava_Programming_by_Example_6th_Edition.pdf
Java_Programming_by_Example_6th_Edition.pdf
 
Lab4
Lab4Lab4
Lab4
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
14 thread
14 thread14 thread
14 thread
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_01-Mar-2021_L12...
 

Recently uploaded

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 

Recently uploaded (20)

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 

STS4022 Exceptional_Handling

  • 1.
  • 3. Exception Handling An exception can occur for following reasons. •User error •Programmer error •Physical error
  • 4. import java.util.*; public class MyClass { public static void main(String args[]) { int x=10; int y=0; int z=x/y; System.out.println(z); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Exception in thread "main" java.lang.ArithmeticException: / by zero at MyClass.main(MyClass.java:6) Output
  • 5. import java.io.*; public class Main { public static void main(String[] args){ System.out.println("First line"); System.out.println("Second line"); int[] myIntArray = new int[]{1, 2, 3}; print(myIntArray); System.out.println("Third line"); } public static void print(int[] arr) { System.out.println(arr[3]); System.out.println("Fourth element successfully displayed!"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 First line Second line Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Main.print(Main.java:11) at Main.main(Main.java:7) Output
  • 7. Types of Exception •Checked Exception •Unchecked Exception
  • 8. //Example for Checked exception import java.io.FileInputStream; public class Main { public static void main(String[] args) { FileInputStream fis = null; fis = new FileInputStream(“D:/myfile.txt"); int k; while(( k = fis.read() ) != -1) { System.out.print((char)k); } fis.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type FileNotFoundException Unhandled exception type IOException Unhandled exception type IOException Output
  • 9. //Example for Unchecked exception import java.io.*; public class Main { public static void main(String[] args){ int[] arr = new int[]{7, 11, 30, 63}; System.out.println(arr[5]); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Main.main(Main.java:5) Output
  • 10. Exception Handling Exception Handling? It is the process of responding to the occurrence during computation of exceptions.
  • 12. import java.util.*; public class MyClass { public static void main(String args[]) { int x=10; int y=0; int z=x/y; System.out.println(z); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.util.*; public class MyClass { public static void main(String args[]) { int x=10; int y=0; try { int z=x/y; } catch(Exception e) { System.out.print(e); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 13. import java.util.*; public class MyClass { public static void main(String args[]) { int x=10; int y=0; try { int z=x/y; } catch(Exception e) { System.out.print(e); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Output: java.lang.ArithmeticException: / by zero Syntax: try { // Protected code } catch (ExceptionName e1) { // Catch block } comment/pseudo code/output
  • 14. import java.io.*; public class Main { public static void main(String[] args){ System.out.println("First line"); System.out.println("Second line"); try{ int[] myIntArray = new int[]{1, 2, 3}; print(myIntArray); } catch (ArrayIndexOutOfBoundsException e){ System.out.println("The array doesn't have fourth element!"); } System.out.println("Third line"); } public static void print(int[] arr) { System.out.println(arr[3]); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 15. First line Second line The array doesn't have fourth element! Third line OUTPUT
  • 16. System.out.print(arr[3]) Internal Working of try-catch Block An object of exception class is thrown JVM • Prints out exception Description • Prints stack trace • Terminates the program rest of code is executed yes Exception object Is Handled? no rest of code is executed yes Exception object Is Handled? no
  • 17. //Predict the Output import java.util.*; public class MyClass { public static void main(String args[]) { MyClass ob = new MyClass(); try { ob.meth1(); } catch(ArithmeticException e) { System.out.println("ArithmaticException thrown by meth1() method is caught in main() method"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 18. public void meth1() { try { System.out.println(100/0); } catch(NullPointerException nullExp) { System.out.println("We have an Exception - "+nullExp); } System.out.println("Outside try-catch block"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 19. import java.util.*; public class MyClass { public static void main(String[] args) { try{ int arr[]=new int[5]; arr[7]=100/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"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 20. //Predict the Output import java.util.*; public class MyClass { public static void main(String[] args) { String[] s = {"Hello", "423", null, "Hi"}; for (int i = 0; i < 5; i++) { try { int a = s[i].length() + Integer.parseInt(s[i]); } catch(NumberFormatException ex) { System.out.println("NumberFormatException"); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 21. catch (ArrayIndexOutOfBoundsException ex) { System.out.println("ArrayIndexOutOfBoundsException"); } catch (NullPointerException ex) { System.out.println("NullPointerException"); } System.out.println("After catch, this statement will be executed"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 22. // Pipe(|) operator import java.util.*; public class Main { public static void main(String[] args) { String[] s = {"abc", "123", null, "xyz"}; for (int i = 0; i < 5; i++) { try { int a = s[i].length() + Integer.parseInt(s[i]); } catch(NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException ex) { System.out.println("Handles above mentioned three Exception"); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 23. //Predict the output import java.util.*; public class Main { public static void main(String[] args) { try { int i = Integer.parseInt("Thor"); } catch(Exception ex) { System.out.println("This block handles all exception types"); } catch(NumberFormatException ex) { System.out.print("This block handles NumberFormatException"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 24. //Predict the OUtput import java.util.*; public class Main { public static void main(String[] args) { String[] str = {null, "Marvel"}; for (int i = 0; i < str.length; i++) { try { int a = str[i].length(); try { a = Integer.parseInt(str[i]); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 26. //Syntax for finally block try { //Statements that may cause an exception } catch { //Handling exception } finally { //Statements to be executed } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 It contains all the crucial statements that must be executed whether exception occurs or not. Description
  • 27. public class MyClass{ public static void main(String args[]){ try{ int data = 30/3; System.out.println(data); } catch(NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 28. public class MyClass { public static void main(String args[]) { try{ int num=121/0; System.out.println(num); } catch(ArithmeticException e){ System.out.println("Number should not be divided by zero"); } finally{ System.out.println("This is finally block"); } System.out.println("Out of try-catch-finally"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 29. public class MyClass { public static void main(String args[]) { System.out.println(MyClass.myMethod()); } public static int myMethod() { try { return 0; } finally { System.out.println("This is Finally block"); System.out.println("Finally block ran even after return statement"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 30. public class MyClass { public static void main(String args[]) { System.out.println(MyClass.myMethod()); } public static int myMethod() { try { return 0; } finally { System.out.println("This is Finally block"); System.out.println("Finally block ran even after return statement"); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 31. Cases when the finally block doesn’t execute • The death of a Thread. • Using of the System. exit() method. • Due to an exception arising in the finally block.
  • 32. public class MyClass{ public static void main(String args[]) { System.out.println(MyClass.myMethod()); } public static int myMethod(){ try { int x = 63; int y = 9; int z=x/y; System.out.println("Inside try block"); System.exit(0); } catch (Exception exp){ System.out.println(exp); } finally{ System.out.println("Java finally block"); return 0; } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 33. public class MyClass{ public static void main(String args[]) { System.out.println(MyClass.myMethod()); } public static int myMethod(){ try { int x = 63; int y = 0; int z=x/y; System.out.println("Inside try block"); System.exit(0); } catch (Exception exp){ System.out.println(exp); } finally{ System.out.println("Java finally block"); return 0; } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 34. //Syntax for throw block throw new exception_class("error message"); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The Java throw keyword is used to explicitly throw an exception. Description
  • 35. public class MyClass { public static void validate(int age) { if(age<21 || age>27) throw new ArithmeticException("not eligible"); else System.out.println("Eligible to attend Military Selection "); } public static void main(String args[]) { validate(30); System.out.println("rest of the code..."); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 36. Exception in thread "main" java.lang.ArithmeticException: not eligible at MyClass.validate(MyClass.java:6) at MyClass.main(MyClass.java:12) OUTPUT
  • 37. public class MyClass { public static void validate(int age) { if(age<21 || age>27) throw new ArithmeticException("not eligible"); else System.out.println("Eligible to attend Military Selection "); } public static void main(String args[]) { try { validate(30); } catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code..."); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 39. public class MyClass { public static void validate(int age) { if(age<21 || age>27) throw new ArithmeticException("not eligible"); else System.out.println("Eligible to attend Military Selection "); } public static void main(String args[]) { try { validate(21); } catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code..."); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 40. Eligible to attend Military Selection rest of the code... OUTPUT

Editor's Notes

  1. 1st slide (Mandatory)
  2. Description: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Consider you are travelling in a car. It represents the normal flow of the program. When the tyre get punctured, it will affect your journey. It represents the exception.
  3. Description: In programming the exception may occur for the following reason’s. User error - A user has entered an invalid data. Programmer error - A file that needs to be opened cannot be found. Physical error - A network connection has been lost in the middle of communications or the JVM has run out of memory
  4. Note: Exception in thread "main" java.lang.ArithmeticException: / by zero at MyClass.main(MyClass.java:6) MyClass : The class name main : The method name MyClass.java : The filename java:6 : Line number Description: Here the exception is raised because we are trying to divide the a number with zero. So an exception is raised. When an exception occur, At first the Exception object will be created. This object contains the necessary information about the error and in which line it is occurred and the nature of the exception. This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. 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.
  5. Description: Here the only three print statement get executed and printed then an exception raises. This interrupts the normal flow of the program i.e.) remaining line of code are not get excecuted.
  6. Description:
  7. Description: Checked Exception: All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc. Unchecked Exception: Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
  8. Description: In this example we are reading the file myfile.txt and displaying its content on the screen. In this program there are three places where a checked exception is thrown as mentioned in the comments below. FileInputStream which is used for specifying the file path and name, throws FileNotFoundException. The read() method which reads the file content throws IOException and the close() method which closes the file input stream also throws IOException.
  9. Description:
  10. Description: Once the exception is occurred i.e.) when car wheel get punctured, it is handled with the help of new set of wheel, jack and spanner.
  11. Description: Once the exception is occurred i.e.) when car wheel get punctured, it is handled with the help of new set of wheel, jack and spanner.
  12. Description: In programming the statement which cause’s the exception are called critical Statement. In order to handle the exception in programming we are using try and catch block. The critical statements are placed inside the try block. When an exception is thrown by an try{…} block . The exception is catched with the help of the catch(){…} block.
  13. Description: try: The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. 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. It can be followed by finally block later.
  14. Description: The array arr[] consist of three elements 1, 2, 3. We are trying to access the array index 3. Since we are trying to access the array index 3. So it will throw an exception called ArrayIndexOutofBoundsException. This exception is catch by catch block. We have handled the exception there is no interruption in program flow then the last print statement also get excecuted.
  15. Description: 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 exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
  16. Output: ArithmaticException thrown by meth1() method is caught in main() method Description: The class MyClass contains two method one is main method() and meth1(). The object is created for the class MyClass inside the main method i.e.) MyClass ob = new MyClass(); Here, an exception of type ArithmeticException is thrown out of try block in meth1() method. This thrown exception is not caught by the catch block defined in the meth1() method, because the catch block has declared a non-matching type of exception i.e. NullPointerException. This uncaught exception is thrown down to the next method in call stack, i.e. main() method( which called meth1() method from within its try-catch block) and it does have a matching catch block to catch the exception thrown by meth1() method and the exception is caught.
  17. Output: Arithmetic Exception occurs rest of the code Description: It is an example of multiple catch block. Java catch multiple exceptions A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. Points to remember: 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.
  18. Output: NumberFormatException After catch, this statement will be executed After catch, this statement will be executed NullPointerException After catch, this statement will be executed NumberFormatException After catch, this statement will be executed ArrayIndexOutOfBoundsException After catch, this statement will be executed
  19. Multiple exceptions thrown by the try block can be handled by a single catch block using pipe (|) operator. Output: Handles above mentioned three Exception Handles above mentioned three Exception Handles above mentioned three Exception Handles above mentioned three Exception
  20. Output: Compilation Error Main.java:14: error: exception NumberFormatException has already been caught Description: The order of catch blocks should be from most specific to most general ones. i.e Sub classes of Exception must come first and super classes later. If you keep the super classes first and sub classes later, you will get compile time error : Unreachable Catch Block.
  21. Output: Compilation Error Main.java:14: error: exception NumberFormatException has already been caught Description: The order of catch blocks should be from most specific to most general ones. i.e Sub classes of Exception must come first and super classes later. If you keep the super classes first and sub classes later, you will get compile time error : Unreachable Catch Block.
  22. Description: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
  23. Output: 10 finally block is always executed Description: Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient for exception handling, however if you place a finally block then it will always run after the execution of try block.
  24. Output: Number should not be divided by zero This is finally block Out of try-catch-finally
  25. Output: This is Finally block Finally block ran even after return statement 0 Description: The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue.
  26. Output: This is Finally block Finally block ran even after return statement 0 Description: The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue.
  27. Output: Inside try block Description: System.exit() statement behaves differently than return statement. Unlike return statement whenever System.exit() gets called in try block then Finally block doesn’t execute. In the above example if the System.exit(0) gets called without any exception then finally won’t execute. 
  28. Output: java.lang.ArithmeticException: / by zero Java finally block 0 Description: Here exception occurs while calling System.exit(0) then finally block will be executed.
  29. Description: The Java throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception
  30. Description: We can define our own set of conditions or rules and throw an exception explicitly using throw keyword.  Here we are defining our exception by giving if the input is greater than the age 21 and less than age 27, we are throwing an exception called Arithmetic exception called not eligible. We are not handling the exception. So the System.out.println(“rest of the code is..”) not executed. Note: Throw keyword is always placed inside the method.
  31. Description: Now you can clearly that the exception raised in the before example is now handled using try and catch block
  32. Description: We can define our own set of conditions or rules and throw an exception explicitly using throw keyword.  Here we are defining our exception by giving if the input is less than the age 18, we are throwing an exception called not valid
  33. Thank you slide