SlideShare a Scribd company logo
1 of 36
1
EXCEPTION
HANDLING
2
• An exception is an abnormal condition that arises in
a code sequence at run-time(run-time error)
• A Java exception is an object that describes an
exceptional (that is, error) condition that has
occurred in a piece of code
• When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error
• The exception is caught and processed
3
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
• Program statements that you want to monitor for
exceptions are contained within a try block
• If an exception occurs within the try block, it is
thrown
• Your code can catch this exception (using catch) and
handle it
4
• System-generated exceptions are automatically
thrown by the Java run-time system
• To manually throw an exception, use the keyword
throw
• Any exception that is thrown out of a method must
be specified as such by a throws clause
• Any code that absolutely must be executed before a
method returns is put in a finally block
5
• This is the general form of an exception-handling
block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1 }
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2 }
// ...
finally {
// block of code to be executed before try block ends }
6
Exception Types
• All exception types are subclasses of the built-in class
Throwable
• Immediately below Throwable are two subclasses
that partition exceptions into two distinct branches
• One branch is headed by Exception
• This class is used for exceptional conditions that user
programs should catch
8
• There is an important subclass of Exception, called
RuntimeException
• Exceptions of this type are automatically defined for
the programs that you write and include things such
as division by zero and invalid array indexing
9
• The other branch is topped by Error, which defines
exceptions that are not expected to be caught under
normal circumstances by your program
• Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the
run-time environment, itself
• Stack overflow is an example of such an error
Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d; } //end of main } //end of cass
• Java run-time constructs a new exception object and
then throws this exception. This causes the execution of
Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and
dealt with immediately.
• The default handler displays a string describing the
exception, prints a stack trace from the point at which
the exception occurred, and terminates the program.
• Output: java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
class Exc1 { //method separated from main()
static void subroutine() {
int d = 0;
int a = 10 / d; }
public static void main(String args[]) {
Exc1.subroutine(); } }
• The resulting stack trace from the default exception
handler shows how the entire call stack is displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:6)
12
Using try and catch:
• Handling an exception manually provides two
benefits
• First, it allows you to fix the error
• Second, it prevents the program from automatically
terminating
• To guard against and handle a run-time error, simply
enclose the code that you want to monitor inside a
try block.
• Immediately following the try block, include a catch
clause that specifies the exception type that you wish
to catch.
13
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed."); }
catch (ArithmeticException e) { // catch divide-by-zero
error
System.out.println("Division by zero."); }
System.out.println("After catch statement."); } }
This program generates the following output:
Division by zero.
After catch statement.
Example 2: ArrayIndexOutOfBounds Exception
Class: Java.lang.ArrayIndexOutOfBoundsException
This is a built in class present in java.lang package. This exception occurs
when the referenced element does not exist in the array. For e.g. If
array is having only 5 elements and we are trying to display 7th element
then it would throw this exception.
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
Example 3: StringIndexOutOfBound Exception
Class: Java.lang.StringIndexOutOfBoundsException
An object of this class gets created whenever an index is
invoked of a string, which is not in the range.
Each character of a string object is stored in a particular index
starting from 0.
To get a character present in a particular index of a string we
can use a method charAt(int) of java.lang.String where int
argument is the index.
E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the
String.
Multiple catch blocks in Java
1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other
exceptions
Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch
block should be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely
ignored and the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will
catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
Types of exceptions
1. Checked exceptions
• 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, it will give compilation
error.
Examples of Checked Exceptions :-
ClassNotFoundException,
IllegalAccessException
IOException
EOFException etc.
2.Unchecked Exceptions
• Runtime Exceptions are also known as Unchecked Exceptions as the compiler do
not check whether the programmer has handled them or not but it’s the duty of the
programmer to handle these exceptions and provide a safe exit.
• These exceptions need not be included in any method’s throws list because
compiler does not check to see if a method handles or throws these exceptions.
Examples of Unchecked Exceptions:-
ArithmeticException,
ArrayIndexOutOfBoundsException,
NullPointerException
etc.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then
program execution can get terminated and system prints a non user friendly error
message.
Ex:-Take a look at the below system generated exception
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
[ExceptionDemo : The class name main : The method name
ExceptionDemo.java : The filename java:5 : Line number]
What is Finally Block
1. A finally statement must be associated with a try statement. It identifies a block of
statements that needs to be executed regardless of whether or not an exception
occurs within the try block.
2. After all other try-catch processing is complete, the code inside the finally block
executes. It is not mandatory to include a finally block at all, but if you do, it will run
regardless of whether an exception was thrown and handled by the try and catch parts
of the block.
3. In normal execution the finally block is executed after try block. When any exception
occurs first the catch block is executed and then finally block is executed.
4. An exception in the finally block, exactly behaves like any other exception.
5. The code present in the finally block executes even if the try or catch block contains
control transfer statements like return, break or continue
Syntax of Finally block
try
{
//statements that may cause an
exception
}
finally
{
//statements to be executed
}
Example: Finally Block
Example 1: Below example illustrates finally block when no exception occurs in try
block
class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block ");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block 15
finally block
Out of try-catch-finally block
Example 2:Below example illustrates finally block execution when exception occurs
in try block but doesn’t get handled in catch block.
class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Example2.main(Details.java:6)
Example 3:Below example illustrates execution of finally, when exception occurs in
try block and handled in catch block.
class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block
Throw vs Throws in java
1. Throws clause in used to declare an exception and throw keyword is used to throw
an exception explicitly.
2. If we see syntax wise, throw is followed by an instance variable and throws is
followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws
clause is used in method declaration (signature).
for e.g.
Throw:
....
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp());
}
}
Throws:
public void sample() throws ArithmeticException{
//Statements
.....
//if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
throw exp;
...
}
4. By using Throw keyword in java you cannot throw more than one exception but
using throws you can declare multiple exceptions..
for e.g.
Throw:
throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
How to throw exception in java with example
(i) In terms of already defined exceptions
(ii) In terms of user defined exceptions
(i) In java we have already defined exception classes such as ArithmeticException,
ArrayIndexOutOfBoundsException, NullPointerException etc. There are certain
conditions defined for these exceptions and on the occurrence of those conditions
they are implicitly thrown by JVM(java virtual machine).
(ii) Do you know that a programmer can create a new exception and throw it
explicitly?
• These exceptions are known as user-defined exceptions. In order to throw user
defined exceptions, throw keyword is being used.
• You can also throw an already defined exception like ArithmeticException,
IOException etc.
How to throw user defined exception in java with example
Example1: How to throw user defined exception using throw keyword
class MyOwnException extends Exception {
public MyOwnException(String msg){
super(msg);
}}
class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
System.out.println(e);
}
}
}
Output:
MyOwnException: Age can't be less than zero
How to throw already defined exception in java with example
Example2: How to throw an already defined exception using throw keyword
class Exception2{
static int sum(int num1, int num2){
if (num1 == 0)
throw new ArithmeticException("First parameter is not valid");
else
System.out.println("Both parameters are correct!!");
return num1+num2;
}
public static void main(String args[]){
int res=sum(0,12);
System.out.println(res);
System.out.println("Continue Next statements");
}
}
Output:
Exception in thread main java.lang.ArithmeticException: First parameter is
not valid
Throws Keyword Example in Java
Exception Handling
As we know that there are two types of exception – checked and
unchecked. Checked exceptions (compile time) are the one which forces
the programmer to handle it, without which the program doesn’t compile
successfully. While unchecked exception (Runtime) doesn’t get checked
during compilation. “Throws keyword” is mainly used for handling
checked exception as using throws we can declare multiple exceptions in
one go. Let’s understand this with the help of an example.
Example of throws Keyword
import java.io.*;
public class ThrowExample {
void mymethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("Exception Message1");
else
throw new ClassNotFoundException("Exception Message2");
}
}
class Demo{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.mymethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException: Exception Message1
35
// This program contains error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[ ]) {
throwOne(); }
}
• To make this to compile-
• you need to declare that throwOne( ) throws
IllegalAccessException.
• main( ) must define a try/catch statement that catches
this exception.
36
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e); } } }
Here is the output generated by running this program:
inside throwOne
caught java.lang.IllegalAccessException: demo

More Related Content

Similar to 8.Exception handling latest(MB).ppt .

Exception
ExceptionException
ExceptionFraboni Ec
 
Exception
ExceptionException
ExceptionJames Wong
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming languageushakiranv110
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 

Similar to 8.Exception handling latest(MB).ppt . (20)

Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 

More from happycocoman

gas turbine cycles.pptx .
gas turbine cycles.pptx                    .gas turbine cycles.pptx                    .
gas turbine cycles.pptx .happycocoman
 
RECIPROCATING_AIR_COMPRESSOR.ppt .
RECIPROCATING_AIR_COMPRESSOR.ppt         .RECIPROCATING_AIR_COMPRESSOR.ppt         .
RECIPROCATING_AIR_COMPRESSOR.ppt .happycocoman
 
SURFACE TEXTURE 2022.pptx .
SURFACE TEXTURE 2022.pptx                  .SURFACE TEXTURE 2022.pptx                  .
SURFACE TEXTURE 2022.pptx .happycocoman
 
Numericals on Raciprocating air compressor.ppt
Numericals on  Raciprocating air compressor.pptNumericals on  Raciprocating air compressor.ppt
Numericals on Raciprocating air compressor.ppthappycocoman
 
Vapor_power cycles KM.pptx ..
Vapor_power cycles KM.pptx            ..Vapor_power cycles KM.pptx            ..
Vapor_power cycles KM.pptx ..happycocoman
 
Vapor power cycles by Anupama.pptx .
Vapor power cycles by Anupama.pptx     .Vapor power cycles by Anupama.pptx     .
Vapor power cycles by Anupama.pptx .happycocoman
 
Performance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.pptPerformance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.ppthappycocoman
 
ICenginesNumericals (1).pptx .
ICenginesNumericals (1).pptx             .ICenginesNumericals (1).pptx             .
ICenginesNumericals (1).pptx .happycocoman
 
Air standard cycles_PPT KM1.pptx .
Air standard cycles_PPT KM1.pptx          .Air standard cycles_PPT KM1.pptx          .
Air standard cycles_PPT KM1.pptx .happycocoman
 
Pressure Measurement ppt.pptx .
Pressure Measurement ppt.pptx               .Pressure Measurement ppt.pptx               .
Pressure Measurement ppt.pptx .happycocoman
 
Measurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxMeasurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxhappycocoman
 
Strain Measurement (NEW).pptx .
Strain Measurement (NEW).pptx               .Strain Measurement (NEW).pptx               .
Strain Measurement (NEW).pptx .happycocoman
 
Force and torque measurements.pptx .
Force and torque measurements.pptx      .Force and torque measurements.pptx      .
Force and torque measurements.pptx .happycocoman
 
FLOW(NEW).pptx .
FLOW(NEW).pptx                          .FLOW(NEW).pptx                          .
FLOW(NEW).pptx .happycocoman
 
Chapter 11 - SCREW THREADS sllides.pdf .
Chapter 11 - SCREW THREADS sllides.pdf       .Chapter 11 - SCREW THREADS sllides.pdf       .
Chapter 11 - SCREW THREADS sllides.pdf .happycocoman
 
Measurement of form errors.pptx .
Measurement of form errors.pptx            .Measurement of form errors.pptx            .
Measurement of form errors.pptx .happycocoman
 
9. Surface Texture - PPT.pdf .
9. Surface Texture - PPT.pdf               .9. Surface Texture - PPT.pdf               .
9. Surface Texture - PPT.pdf .happycocoman
 
10. Screw Threads - PPT.pdf .
10. Screw Threads - PPT.pdf                    .10. Screw Threads - PPT.pdf                    .
10. Screw Threads - PPT.pdf .happycocoman
 
Measurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfMeasurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfhappycocoman
 
Limits Fits and Tolerances ppt.pdf .
Limits Fits and Tolerances ppt.pdf     .Limits Fits and Tolerances ppt.pdf     .
Limits Fits and Tolerances ppt.pdf .happycocoman
 

More from happycocoman (20)

gas turbine cycles.pptx .
gas turbine cycles.pptx                    .gas turbine cycles.pptx                    .
gas turbine cycles.pptx .
 
RECIPROCATING_AIR_COMPRESSOR.ppt .
RECIPROCATING_AIR_COMPRESSOR.ppt         .RECIPROCATING_AIR_COMPRESSOR.ppt         .
RECIPROCATING_AIR_COMPRESSOR.ppt .
 
SURFACE TEXTURE 2022.pptx .
SURFACE TEXTURE 2022.pptx                  .SURFACE TEXTURE 2022.pptx                  .
SURFACE TEXTURE 2022.pptx .
 
Numericals on Raciprocating air compressor.ppt
Numericals on  Raciprocating air compressor.pptNumericals on  Raciprocating air compressor.ppt
Numericals on Raciprocating air compressor.ppt
 
Vapor_power cycles KM.pptx ..
Vapor_power cycles KM.pptx            ..Vapor_power cycles KM.pptx            ..
Vapor_power cycles KM.pptx ..
 
Vapor power cycles by Anupama.pptx .
Vapor power cycles by Anupama.pptx     .Vapor power cycles by Anupama.pptx     .
Vapor power cycles by Anupama.pptx .
 
Performance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.pptPerformance and Testing of Internal Combustion Engines.ppt
Performance and Testing of Internal Combustion Engines.ppt
 
ICenginesNumericals (1).pptx .
ICenginesNumericals (1).pptx             .ICenginesNumericals (1).pptx             .
ICenginesNumericals (1).pptx .
 
Air standard cycles_PPT KM1.pptx .
Air standard cycles_PPT KM1.pptx          .Air standard cycles_PPT KM1.pptx          .
Air standard cycles_PPT KM1.pptx .
 
Pressure Measurement ppt.pptx .
Pressure Measurement ppt.pptx               .Pressure Measurement ppt.pptx               .
Pressure Measurement ppt.pptx .
 
Measurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptxMeasurements & Measurement .Systems.pptx
Measurements & Measurement .Systems.pptx
 
Strain Measurement (NEW).pptx .
Strain Measurement (NEW).pptx               .Strain Measurement (NEW).pptx               .
Strain Measurement (NEW).pptx .
 
Force and torque measurements.pptx .
Force and torque measurements.pptx      .Force and torque measurements.pptx      .
Force and torque measurements.pptx .
 
FLOW(NEW).pptx .
FLOW(NEW).pptx                          .FLOW(NEW).pptx                          .
FLOW(NEW).pptx .
 
Chapter 11 - SCREW THREADS sllides.pdf .
Chapter 11 - SCREW THREADS sllides.pdf       .Chapter 11 - SCREW THREADS sllides.pdf       .
Chapter 11 - SCREW THREADS sllides.pdf .
 
Measurement of form errors.pptx .
Measurement of form errors.pptx            .Measurement of form errors.pptx            .
Measurement of form errors.pptx .
 
9. Surface Texture - PPT.pdf .
9. Surface Texture - PPT.pdf               .9. Surface Texture - PPT.pdf               .
9. Surface Texture - PPT.pdf .
 
10. Screw Threads - PPT.pdf .
10. Screw Threads - PPT.pdf                    .10. Screw Threads - PPT.pdf                    .
10. Screw Threads - PPT.pdf .
 
Measurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdfMeasurement of Form errors complete slides.pdf
Measurement of Form errors complete slides.pdf
 
Limits Fits and Tolerances ppt.pdf .
Limits Fits and Tolerances ppt.pdf     .Limits Fits and Tolerances ppt.pdf     .
Limits Fits and Tolerances ppt.pdf .
 

Recently uploaded

VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 

Recently uploaded (20)

VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 

8.Exception handling latest(MB).ppt .

  • 2. 2 • An exception is an abnormal condition that arises in a code sequence at run-time(run-time error) • A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code • When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error • The exception is caught and processed
  • 3. 3 • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally • Program statements that you want to monitor for exceptions are contained within a try block • If an exception occurs within the try block, it is thrown • Your code can catch this exception (using catch) and handle it
  • 4. 4 • System-generated exceptions are automatically thrown by the Java run-time system • To manually throw an exception, use the keyword throw • Any exception that is thrown out of a method must be specified as such by a throws clause • Any code that absolutely must be executed before a method returns is put in a finally block
  • 5. 5 • This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends }
  • 6. 6 Exception Types • All exception types are subclasses of the built-in class Throwable • Immediately below Throwable are two subclasses that partition exceptions into two distinct branches • One branch is headed by Exception • This class is used for exceptional conditions that user programs should catch
  • 7.
  • 8. 8 • There is an important subclass of Exception, called RuntimeException • Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing
  • 9. 9 • The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program • Exceptions of type Error are used by the Java run- time system to indicate errors having to do with the run-time environment, itself • Stack overflow is an example of such an error
  • 10. Uncaught Exceptions class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } //end of main } //end of cass • Java run-time constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. • The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.
  • 11. • Output: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) class Exc1 { //method separated from main() static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } } • The resulting stack trace from the default exception handler shows how the entire call stack is displayed: java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:6)
  • 12. 12 Using try and catch: • Handling an exception manually provides two benefits • First, it allows you to fix the error • Second, it prevents the program from automatically terminating • To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. • Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.
  • 13. 13 class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement.
  • 14. Example 2: ArrayIndexOutOfBounds Exception Class: Java.lang.ArrayIndexOutOfBoundsException This is a built in class present in java.lang package. This exception occurs when the referenced element does not exist in the array. For e.g. If array is having only 5 elements and we are trying to display 7th element then it would throw this exception.
  • 15. class ExceptionDemo2 { public static void main(String args[]) { try{ int a[]=new int[10]; //Array has only 10 elements a[11] = 9; } catch(ArrayIndexOutOfBoundsException e){ System.out.println ("ArrayIndexOutOfBounds"); } } } Output: ArrayIndexOutOfBounds
  • 16. Example 3: StringIndexOutOfBound Exception Class: Java.lang.StringIndexOutOfBoundsException An object of this class gets created whenever an index is invoked of a string, which is not in the range. Each character of a string object is stored in a particular index starting from 0. To get a character present in a particular index of a string we can use a method charAt(int) of java.lang.String where int argument is the index.
  • 17. E.g. class ExceptionDemo4 { public static void main(String args[]) { try{ String str="easysteps2buildwebsite"; System.out.println(str.length());; char c = str.charAt(0); c = str.charAt(40); System.out.println(c); }catch(StringIndexOutOfBoundsException e){ System.out.println("StringIndexOutOfBoundsException!!"); } } } Output: StringIndexOutOfBoundsException!! Exception occurred because the referenced index was not present in the String.
  • 18. Multiple catch blocks in Java 1. A try block can have any number of catch blocks. 2. A catch block that is written for catching the class Exception can catch all other exceptions Syntax: catch(Exception e){ //This catch block catches all the exceptions } 3. If multiple catch blocks are present in a program then the above mentioned catch block should be placed at the last as per the exception handling best practices. 4. If the try block is not throwing any exception, the catch block will be completely ignored and the program continues. 5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it –catch(ArithmeticException e) is a catch block that can catch ArithmeticException –catch(NullPointerException e) is a catch block that can catch NullPointerException 6. All the statements in the catch block will be executed and then the program continues.
  • 19. class Example2{ public static void main(String args[]){ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } } Output: Warning: ArithmeticException Out of try-catch block...
  • 20. Types of exceptions 1. Checked exceptions • 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, it will give compilation error. Examples of Checked Exceptions :- ClassNotFoundException, IllegalAccessException IOException EOFException etc.
  • 21. 2.Unchecked Exceptions • Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit. • These exceptions need not be included in any method’s throws list because compiler does not check to see if a method handles or throws these exceptions. Examples of Unchecked Exceptions:- ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException etc.
  • 22. Why to handle exception? If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message. Ex:-Take a look at the below system generated exception An exception generated by the system is given below Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5) [ExceptionDemo : The class name main : The method name ExceptionDemo.java : The filename java:5 : Line number]
  • 23. What is Finally Block 1. A finally statement must be associated with a try statement. It identifies a block of statements that needs to be executed regardless of whether or not an exception occurs within the try block. 2. After all other try-catch processing is complete, the code inside the finally block executes. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block. 3. In normal execution the finally block is executed after try block. When any exception occurs first the catch block is executed and then finally block is executed. 4. An exception in the finally block, exactly behaves like any other exception. 5. The code present in the finally block executes even if the try or catch block contains control transfer statements like return, break or continue
  • 24. Syntax of Finally block try { //statements that may cause an exception } finally { //statements to be executed }
  • 25. Example: Finally Block Example 1: Below example illustrates finally block when no exception occurs in try block class Example1{ public static void main(String args[]){ try{ System.out.println("First statement of try block "); int num=45/3; System.out.println(num); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("ArrayIndexOutOfBoundsException"); } finally{ System.out.println("finally block"); } System.out.println("Out of try-catch-finally block"); } } Output: First statement of try block 15 finally block Out of try-catch-finally block
  • 26. Example 2:Below example illustrates finally block execution when exception occurs in try block but doesn’t get handled in catch block. class Example2{ public static void main(String args[]){ try{ System.out.println("First statement of try block"); int num=45/0; System.out.println(num); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("ArrayIndexOutOfBoundsException"); } finally{ System.out.println("finally block"); } System.out.println("Out of try-catch-finally block"); } } Output: First statement of try block finally block Exception in thread "main" java.lang.ArithmeticException: / by zero at Example2.main(Details.java:6)
  • 27. Example 3:Below example illustrates execution of finally, when exception occurs in try block and handled in catch block. class Example3{ public static void main(String args[]){ try{ System.out.println("First statement of try block"); int num=45/0; System.out.println(num); } catch(ArithmeticException e){ System.out.println("ArithmeticException"); } finally{ System.out.println("finally block"); } System.out.println("Out of try-catch-finally block"); } } Output: First statement of try block ArithmeticException finally block Out of try-catch-finally block
  • 28. Throw vs Throws in java 1. Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly. 2. If we see syntax wise, throw is followed by an instance variable and throws is followed by exception class names. 3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature). for e.g. Throw: .... static{ try { throw new Exception("Something went wrong!!"); } catch (Exception exp) { System.out.println("Error: "+exp()); } }
  • 29. Throws: public void sample() throws ArithmeticException{ //Statements ..... //if (Condition : There is an error) ArithmeticException exp = new ArithmeticException(); throw exp; ... } 4. By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions.. for e.g. Throw: throw new ArithmeticException("An integer should not be divided by zero!!") throw new IOException("Connection failed!!") Throws: throws IOException, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
  • 30. How to throw exception in java with example (i) In terms of already defined exceptions (ii) In terms of user defined exceptions (i) In java we have already defined exception classes such as ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException etc. There are certain conditions defined for these exceptions and on the occurrence of those conditions they are implicitly thrown by JVM(java virtual machine). (ii) Do you know that a programmer can create a new exception and throw it explicitly? • These exceptions are known as user-defined exceptions. In order to throw user defined exceptions, throw keyword is being used. • You can also throw an already defined exception like ArithmeticException, IOException etc.
  • 31. How to throw user defined exception in java with example Example1: How to throw user defined exception using throw keyword class MyOwnException extends Exception { public MyOwnException(String msg){ super(msg); }} class EmployeeTest { static void employeeAge(int age) throws MyOwnException{ if(age < 0) throw new MyOwnException("Age can't be less than zero"); else System.out.println("Input is valid!!"); } public static void main(String[] args) { try { employeeAge(-2); } catch (MyOwnException e) { System.out.println(e); } } } Output: MyOwnException: Age can't be less than zero
  • 32. How to throw already defined exception in java with example Example2: How to throw an already defined exception using throw keyword class Exception2{ static int sum(int num1, int num2){ if (num1 == 0) throw new ArithmeticException("First parameter is not valid"); else System.out.println("Both parameters are correct!!"); return num1+num2; } public static void main(String args[]){ int res=sum(0,12); System.out.println(res); System.out.println("Continue Next statements"); } } Output: Exception in thread main java.lang.ArithmeticException: First parameter is not valid
  • 33. Throws Keyword Example in Java Exception Handling As we know that there are two types of exception – checked and unchecked. Checked exceptions (compile time) are the one which forces the programmer to handle it, without which the program doesn’t compile successfully. While unchecked exception (Runtime) doesn’t get checked during compilation. “Throws keyword” is mainly used for handling checked exception as using throws we can declare multiple exceptions in one go. Let’s understand this with the help of an example.
  • 34. Example of throws Keyword import java.io.*; public class ThrowExample { void mymethod(int num)throws IOException, ClassNotFoundException{ if(num==1) throw new IOException("Exception Message1"); else throw new ClassNotFoundException("Exception Message2"); } } class Demo{ public static void main(String args[]){ try{ ThrowExample obj=new ThrowExample(); obj.mymethod(1); }catch(Exception ex){ System.out.println(ex); } } } Output: java.io.IOException: Exception Message1
  • 35. 35 // This program contains error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[ ]) { throwOne(); } } • To make this to compile- • you need to declare that throwOne( ) throws IllegalAccessException. • main( ) must define a try/catch statement that catches this exception.
  • 36. 36 class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this program: inside throwOne caught java.lang.IllegalAccessException: demo

Editor's Notes

  1. Exception handling fundamentals, types of exceptions, example code which monitors and handles exception, user-defined exception
  2. In simple terms, a stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.
  3. try{//null pointer String str=null; System.out.println (str.length()); }catch(NullPointerException e){ System.out.println("NullPointerException..");
  4. IllegalAccess: trying to access private member outside, accessing static member in a normal method etc. IOException: file not found or reading beyond file size
  5. Attempt to access the value of an object assigned with NULL
  6. **
  7. *
  8. *public String toString(){//overriding the toString() method     return rollno+" "+name+" "+city;    } Â