SlideShare uma empresa Scribd logo
1 de 28
Exception Handling in Java
 Exception
 Exception is an abnormal condition that arises at run time
 Event that disrupts the normal flow of the program.
 It is an object which is thrown at runtime.
 Exception Handling
 Exception Handling is a mechanism to handle runtime errors.
 Normal flow of the application can be maintained.
 It is an object which is thrown at runtime.
 Exception handling done with the exception object.
There are three categories of errors:
 Syntax errors - arise because the rules of the language have not been
followed. They are detected by the compiler.
 Runtime errors - occur while the program is running if the
environment detects an operation that is impossible to carry out.
 Logic errors - occur when a program doesn't perform the way it was
intended to.
Types of Errors
 Types of Exception:
 There are mainly two types of exceptions:
 Checked
 Unchecked – Eg. error
 The sun microsystem says there are three types of exceptions:
 Checked Exception - are checked at compile-time.
 Unchecked Exception - are not checked at compile-time rather
they are checked at runtime.
 Error
 Checked Exception - Classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions.
Checked Exceptions means that compiler forces the programmer to
check and deal with the exceptions. e.g.IOException, SQLException
etc.
 Unchecked Exception - Classes that extends RuntimeException, Error
and their subclasses are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException, ArrayIndexOutOf Bounds
Exception etc.
 Error is irrecoverable should not try to catch. e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Exception Classes
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
6
System Errors
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur.
7
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exceptions
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
8
Runtime Exceptions
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-
bounds array, and numeric errors.
Exception Handling Terms
 try – used to enclose a segment of code that may produce a
exception
 throw – to generate an exception or to describe an instance of an
exception
 catch – placed directly after the try block to handle one or more
exception types
 finally – optional statement used after a try-catch block to run a
segment of code regardless if a exception is generated
Exceptions –Syntax
try
{
// Code which might throw an exception
}
catch(Exceptionclass object1)
{
// code to handle an exception
}
catch(Exceptionclass object2)
{
// code to handle an exception
}
finally
{
// ALWAYS executed whether an exception was thrown or not
}
class Simple
{
public static void main(String args[])
{
int data=50/0;
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Rest of the code is not executed (rest of the code..)statement is not printed.
 JVM first 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.
 if exception is handled by the application programmer, normal flow of
the application is maintained i.e. rest of the code is executed.
class Simple1
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code…
Multiple catch block:
 If more than one exception can occur, then we use multiple catch
blocks
 When an exception is thrown, each catch statement is inspected in
order, and the first one whose type matches that of the exception is
executed
 After one catch statement executes, the others are bypassed
Multiple Catch Exceptions –Syntax
try
{
// Code which might throw an exception
}
catch(Exceptionclass object1)
{
// code to handle an exception
}
catch(Exceptionclass object2)
{
// code to handle an exception
}
Nested try Statements
 A try statement can be inside the block of another try
 Each time a try statement is entered, the context of that exception
is pushed on the stack
 If an inner try statement does not have a catch, then the next try
statement’s catch handlers are inspected for a match
 If a method call within a try block has try block within it, then then
it is still nested try
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Nested Try Block
class Excep6
{
public static void main(String args[])
{
try
{
try
{
S.o.p("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
 Finally block
 is a block that is always executed.
 To perform some important tasks such as closing connection, stream etc.
 Used to put "cleanup" code such as closing a file, closing connection etc.
 Finally creates a block of code that will be executed after a try/catch block
has completed
 Finally block will be executed whether or not an exception is thrown.
 Each try clause requires at least one catch or finally clause.
 Note: Before terminating the program, JVM executes finally block(if any).
 Note: finally must be followed by try or catch block.
class Simple
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}}
 throw keyword
 keyword is used to explictily throw an exception / custom exception.
throw new ExceptionName("Error Message");
 Throw either checked or uncheked exception.
throw new ThrowableInstance
 ThrowableInstance must be an object of type Throwable /
subclass Throwable
 There are two ways to obtain a Throwable objects:
 Using a parameter into a catch clause
 Creating one with the new operator
public class bank
{
public static void main(String args[])
{
int balance = 100, withdraw = 1000;
if(balance < withdraw)
{
//ArithmeticException e = new ArithmeticException("No money please");
//throw e;
//throw new ArithmeticException();
throw new ArithmeticException("No Money");
}
else
{
System.out.println("Draw & enjoy Sir, Best wishes of the day");
}
}
}
import java.io.*;
public class Example
{
public static void main(String args[]) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int x = Integer.parseInt(dis.readLine());
if(x < 0)
{
throw new IllegalArgumentException();
throw new IllegalArgumentException
("You have entered no"+" "+ x +" "+ "which is less than 0");
}
else
{
System.out.println("The no is"+x);
}
}
}
throws
 If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the method
can guard themselves against that exception
type method-name parameter-list) throws exception-list
{
// body of method
}
 It is not applicable for Error or RuntimeException, or any of their
subclasses
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything
E.g: VirtualMachineError or StackOverflowError.
throw keyword throws keyword
throw is used to explicitly throw an
exception.
throws is used to declare an exception.
checked exception can not be propagated
without throws.
checked exception can be propagated
with throws.
throw is followed by an instance. throws is followed by class.
throw is used within the method.
throws is used with the method
signature.
You cannot throw multiple exception
You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.
class NumberRangeException extends Exception
{
String msg;
NumberRangeException()
{
msg = new String("Enter a number between 20 and 100");
}
}
Create our Own Exception:
public class My_Exception
{
public static void main (String args [ ])
{
try
{
int x = 10;
if (x < 20 || x >100) throw new NumberRangeException( );
}
catch (NumberRangeException e)
{
System.out.println (e);
}
}
}

Mais conteúdo relacionado

Mais procurados (20)

Java exception
Java exception Java exception
Java exception
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
String in java
String in javaString in java
String in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Interface in java
Interface in javaInterface in java
Interface in java
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 

Semelhante a Java exception handling

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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
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
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 

Semelhante a Java exception handling (20)

java exception.pptx
java exception.pptxjava exception.pptx
java exception.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
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exception handling in java
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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 

Mais de BHUVIJAYAVELU

Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...
Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...
Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...BHUVIJAYAVELU
 
Flow control and error control
Flow control and error controlFlow control and error control
Flow control and error controlBHUVIJAYAVELU
 
3 2--power-aware-cloud
3 2--power-aware-cloud3 2--power-aware-cloud
3 2--power-aware-cloudBHUVIJAYAVELU
 

Mais de BHUVIJAYAVELU (9)

Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...
Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...
Eprojectprojectfinalreportgsmmonitoringcontrollingofdevicesusinggsm 090811012...
 
Lecture no1
Lecture no1Lecture no1
Lecture no1
 
Java arrays
Java arraysJava arrays
Java arrays
 
Hybrid m-a-t
Hybrid m-a-tHybrid m-a-t
Hybrid m-a-t
 
Java interface
Java interfaceJava interface
Java interface
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java packages
Java packagesJava packages
Java packages
 
Flow control and error control
Flow control and error controlFlow control and error control
Flow control and error control
 
3 2--power-aware-cloud
3 2--power-aware-cloud3 2--power-aware-cloud
3 2--power-aware-cloud
 

Java exception handling

  • 1. Exception Handling in Java  Exception  Exception is an abnormal condition that arises at run time  Event that disrupts the normal flow of the program.  It is an object which is thrown at runtime.  Exception Handling  Exception Handling is a mechanism to handle runtime errors.  Normal flow of the application can be maintained.  It is an object which is thrown at runtime.  Exception handling done with the exception object.
  • 2. There are three categories of errors:  Syntax errors - arise because the rules of the language have not been followed. They are detected by the compiler.  Runtime errors - occur while the program is running if the environment detects an operation that is impossible to carry out.  Logic errors - occur when a program doesn't perform the way it was intended to. Types of Errors
  • 3.  Types of Exception:  There are mainly two types of exceptions:  Checked  Unchecked – Eg. error  The sun microsystem says there are three types of exceptions:  Checked Exception - are checked at compile-time.  Unchecked Exception - are not checked at compile-time rather they are checked at runtime.  Error
  • 4.  Checked Exception - Classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. Checked Exceptions means that compiler forces the programmer to check and deal with the exceptions. e.g.IOException, SQLException etc.  Unchecked Exception - Classes that extends RuntimeException, Error and their subclasses are known as unchecked exceptions e.g. ArithmeticException,NullPointerException, ArrayIndexOutOf Bounds Exception etc.  Error is irrecoverable should not try to catch. e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 6. 6 System Errors LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur.
  • 7. 7 LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 8. 8 Runtime Exceptions LinkageError Error AWTError AWTException Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Several more classes Several more classes Several more classes IllegalArgumentException RuntimeException is caused by programming errors, such as bad casting, accessing an out-of- bounds array, and numeric errors.
  • 9. Exception Handling Terms  try – used to enclose a segment of code that may produce a exception  throw – to generate an exception or to describe an instance of an exception  catch – placed directly after the try block to handle one or more exception types  finally – optional statement used after a try-catch block to run a segment of code regardless if a exception is generated
  • 10. Exceptions –Syntax try { // Code which might throw an exception } catch(Exceptionclass object1) { // code to handle an exception } catch(Exceptionclass object2) { // code to handle an exception } finally { // ALWAYS executed whether an exception was thrown or not }
  • 11. class Simple { public static void main(String args[]) { int data=50/0; System.out.println("rest of the code..."); } } Output: Exception in thread main java.lang.ArithmeticException:/ by zero Rest of the code is not executed (rest of the code..)statement is not printed.
  • 12.  JVM first 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.  if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
  • 13. class Simple1 { public static void main(String args[]) { try { int data=50/0; } catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code..."); }} Output: Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code…
  • 14. Multiple catch block:  If more than one exception can occur, then we use multiple catch blocks  When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed  After one catch statement executes, the others are bypassed
  • 15. Multiple Catch Exceptions –Syntax try { // Code which might throw an exception } catch(Exceptionclass object1) { // code to handle an exception } catch(Exceptionclass object2) { // code to handle an exception }
  • 16. Nested try Statements  A try statement can be inside the block of another try  Each time a try statement is entered, the context of that exception is pushed on the stack  If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match  If a method call within a try block has try block within it, then then it is still nested try
  • 17. try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } catch(Exception e) { } Nested Try Block
  • 18. class Excep6 { public static void main(String args[]) { try { try { S.o.p("going to divide"); int b =39/0; } catch(ArithmeticException e) { System.out.println(e); } try { int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); } catch(Exception e) { System.out.println("handeled"); } System.out.println("normal flow.."); } }
  • 19.  Finally block  is a block that is always executed.  To perform some important tasks such as closing connection, stream etc.  Used to put "cleanup" code such as closing a file, closing connection etc.  Finally creates a block of code that will be executed after a try/catch block has completed  Finally block will be executed whether or not an exception is thrown.  Each try clause requires at least one catch or finally clause.  Note: Before terminating the program, JVM executes finally block(if any).  Note: finally must be followed by try or catch block.
  • 20.
  • 21. class Simple { public static void main(String args[]) { try { int data=25/0; System.out.println(data); } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); }}
  • 22.  throw keyword  keyword is used to explictily throw an exception / custom exception. throw new ExceptionName("Error Message");  Throw either checked or uncheked exception. throw new ThrowableInstance  ThrowableInstance must be an object of type Throwable / subclass Throwable  There are two ways to obtain a Throwable objects:  Using a parameter into a catch clause  Creating one with the new operator
  • 23. public class bank { public static void main(String args[]) { int balance = 100, withdraw = 1000; if(balance < withdraw) { //ArithmeticException e = new ArithmeticException("No money please"); //throw e; //throw new ArithmeticException(); throw new ArithmeticException("No Money"); } else { System.out.println("Draw & enjoy Sir, Best wishes of the day"); } } }
  • 24. import java.io.*; public class Example { public static void main(String args[]) throws IOException { DataInputStream dis=new DataInputStream(System.in); int x = Integer.parseInt(dis.readLine()); if(x < 0) { throw new IllegalArgumentException(); throw new IllegalArgumentException ("You have entered no"+" "+ x +" "+ "which is less than 0"); } else { System.out.println("The no is"+x); } } }
  • 25. throws  If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method }  It is not applicable for Error or RuntimeException, or any of their subclasses
  • 26. unchecked Exception: under your control so correct your code. error: beyond your control e.g. you are unable to do anything E.g: VirtualMachineError or StackOverflowError. throw keyword throws keyword throw is used to explicitly throw an exception. throws is used to declare an exception. checked exception can not be propagated without throws. checked exception can be propagated with throws. throw is followed by an instance. throws is followed by class. throw is used within the method. throws is used with the method signature. You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException.
  • 27. class NumberRangeException extends Exception { String msg; NumberRangeException() { msg = new String("Enter a number between 20 and 100"); } } Create our Own Exception:
  • 28. public class My_Exception { public static void main (String args [ ]) { try { int x = 10; if (x < 20 || x >100) throw new NumberRangeException( ); } catch (NumberRangeException e) { System.out.println (e); } } }