IT1202 Fundamentals of Programming Error Handling in Java - PowerPoint PPT Presentation

1 / 45
About This Presentation
Title:

IT1202 Fundamentals of Programming Error Handling in Java

Description:

IOException. RuntimeException. Error. Parent class of exception class hierarchy is throwable class. ... IOException. RuntimeException. Error ... – PowerPoint PPT presentation

Number of Views:50
Avg rating:3.0/5.0
Slides: 46
Provided by: niyomal
Category:

less

Transcript and Presenter's Notes

Title: IT1202 Fundamentals of Programming Error Handling in Java


1
IT1202 - Fundamentals of ProgrammingError
Handling in Java
2
Error Handling
  • Programmers in any programming language wish to
    write bug free programs
  • What is a Bug?
  • Bug is a word which used in programming world to
    indicate some error situation in a program

3
Error Handling
  • In a real software program, errors can occur due
    to
  • Programmers dont consider all the situations
    that problems might occur
  • Situations where programmers dont test the
    written programs well
  • Some situations which are out of the programmers
    control

4
Error Handling
  • Problems that might cause to crash a program
  • Improper arithmetic operations - division by zero
    problem
  • Array subscripting problem
  • Bad data from users
  • Corrupt files
  • Network connection failures
  • Hardware devices that dont respond

5
Error Handling in Java
  • In Java these sorts of strange events that may
    cause a program to fail are called..
  • Exceptions

Exceptions
Exceptions
6
Error Handling in Java
Java treatment of an exception
  • If exception occurs and a handler is in effect
  • Flow of control is transferred to the handler
  • After handler completes flow of control continues
    with the statement following the handler
  • If exception occurs and there is no handler for
    it
  • The program terminates

7
Error Handling in Java
  • Most programming languages requires much more
    work to handle error conditions than handling
    program
  • Error management can become a major problem when
    start creating larger systems
  • In some other programming languages normal codes
    like if..else..if or switch are used to control
    errors

8
Error Handling in Java
  • Lets consider the following program

int status loadTextfile() If(status !
1)//there is a problem switch(status) case 2
//file not found case 3 // disk error case 4
// file corrupted default // other
error else // file is loaded
9
Error Handling in Java
  • Problems of using bad error handling mechanisms
  • Errors can be manipulated Inconsistently
  • Different programmers may use different special
    values for handling errors like errno or goto()
    like statements
  • Code to manage these kinds of errors can often
    obscure the programs original intent making
    that code difficult to read and maintain

10
Error Handling in Java
  • In Java also we have if else if like syntax
    to perform some other work but not to handle
    errors
  • Java language introduces a better way to deal
    with exceptional circumstances

11
Error Handling in Java
  • Java language introduces a better way to deal
    with exceptional circumstances with
  • a special language features
  • Consistency checking at compile time
  • a group of classes called exceptions

12
Error Handling in Java
  • Using those features
  • We can add a new behavior and design to our
    classes ( overall system)
  • Our class definitions will describe how our
    program be behaved given the best circumstances
  • We can consistently describe how the program will
    behave when errors are gernerated

13
Error Handling in Java
  • Java exception are actual objects and the
    instances of classes that inherit from the class
    is throwable

14
Error Handling in Java
  • Exceptions can be generated by
  • The Java run-time system
  • Manually generated by your code

15
Error Handling in Java
Java Exception class hierarchy
16
Error Handling in Java
Java Exception class hierarchy
Parent class of exception class hierarchy is
throwable class. It is divided into two
subclasses.
17
Error Handling in Java
Java Exception class hierarchy
Instances of Error are internal errors in the
Java Runtime Environment.These errors are rare
and usually fatal. Users can do nothing about
them. But they are there so we can use them if
it is needed.
18
Error Handling in Java
Java Exception class hierarchy
Exception class fall into two general groups.
19
Error Handling in Java
Java Exception class hierarchy
Subclasses of RuntimeExceptions usually occur due
to errors in code. ArrayIndexOutofBounds NullPoint
erException
20
Error Handling in Java
Java Exception class Hierarchy
Subclasses of IOExceptions indicate that
something strange and out of control things are
happening. 1. EOFException 2. FileNotFoundExceptio
n
21
Error Handling in Java...
  • Exceptions are arranged in a hierarchy like other
    classes
  • Exception super classes indicate more general
    errors
  • Exception sub classes indicate more specific
    errors

Understanding of the organization of these
classes are very important when we deal with
exceptions in our own code
22
Error Handling in Java...
  • Most of the exceptions are part of the java.lang
    package
  • Throwable
  • Exception
  • RuntimeException
  • In some other packages also some exceptions are
    defined Eg java.io package
  • IOException

23
Error Handling in Java...
  • Now we know about exceptions

How do we manage/handle them in our code
24
Error Handling in Java
  • In many cases Java run time enforces Exception
    Management when we try to use methods with
    potential exceptions circumstances
  • it is necessary to handle those exceptions within
    the code, or that code will not get executed at
    all

25
Error Handling in Java...
class DivideZero public static void
main(String args) int
x4,y0 int a x / y System.out.println(a
)
Code is not protected using try Block y 0
26
Error Handling in Java...
27
Error Handling in Java
  • When you have program written with possibilities
    of generating exceptions
  • You can catch an exception
  • You can throw an exception

28
Error Handling in Java
  • To catch an exception one can do two things
  • Protect the code that contains the method that
    might throw an exception inside try block
  • Test for and deal with an exception inside a
    catch block

29
Error Handling in Java
  • Try block try to run a set of code that might
    cause an exception. if it is executed well then
    go on with the program but if it fails due to an
    error then catch the exception and deal with it

30
Error Handling in Java...
Class DivideZero static int anyMethod (int x,
int y) try int a x / y return
a catch (ArithmeticException e)
System.out.println(Division by Zero )
Code is protected using try Block
Exception is caught and handled using catch block
31
Error Handling in Java...
  • Displaying a description of an exception
  • E.g.
  • catch (ArithmeticException e)
  • System.out.println(Exception e)
  • Exception is passed as an argument in a println()
    statement

32
Error Handling in Java...
Multiple catch Clauses
  • When more than one exceptions are raised by a
    single piece of code you can specify two or more
    catch clauses, each catching a different type of
    exception
  • When you use multiple catch statements, then
    exception subclasses which are not belong to a
    one super class are used
  • If the exceptions are belong to the same super
    class then that super class may be used instead
    of writing each and every sub class

33
Error Handling in Java...
Multiple catch Clauses Example
Try //code that might generate
exceptions catch(IOException e) //here handle
IO exceptions catch(ClassNotFoundException
e2) // here handle class not found
exceptions catch(InterruptedException
e3) //handle interrupted exceptions
34
Error Handling in Java...
finally clause
  • If there is a piece of code that should be
    executed whether an exception occurs or not then
  • include it within the optional finally clause of
    the try..catch block

35
Error Handling in Java...
finally clause - Example
  • try
  • readTextfile()
  • catch(IOException e)
  • //deal with IO erros
  • finally
  • closeTextfile()

36
Error Handling in Java...
throws clause
  • used to indicate that a method might throw an
    exception
  • Used after the signature of a method (before the
    opening curly bracket)
  • if multiple Exceptions are thrown, include them
    in throws clause separated by commas

37
Error Handling in Java...
throws clause - Usage
int myMethod (int x, int y) throws
Exception1,Exception2

38
Error Handling in Java...
throws clause - Example
  • public static void main(String args) throws
    IOException BufferedReader stdin new
    BufferedReader( new InputStreamReader(System.in))
  • System.out.print("Filename ")
  • String s stdin.readLine()
  • BufferedReader filein new BufferedReader(
  • new FileReader(s))
  • int a Integer.parseInt(filein.readLine())
  • int b Integer.parseInt(filein.readLine())
  • System.out.println( a / b )

39
Error Handling in Java...
throws clause
  • throws clause provide some extra information
    about the method definition about potential
    exceptions
  • By adding throws clause Java make sure the method
    is being used correctly by other people

40
Error Handling in Java...
throws clause
  • All the instances of exceptions are not necessary
    to list
  • Implicit exception
  • RuntimeException
  • Error
  • Implicit exceptions are thrown by Java runtime
    itself
  • Explicit exceptions are potential candidates of
    our throws clause

41
Error Handling in Java...
Creating your own exception
  • When creating new exception it should inherit
    form some other exception from the exception
    hierarchy
  • Exceptions of error hierarchy can not be
    inherited

42
Error Handling in Java...
Creating your own exception
public class SunSpotException extends
Exception public SunSpotException()
public SunSpotExceotion(String msg)
super(msg)
Defining Exception
43
Error Handling in Java...
When not to use exceptions
  • When the exception is expected and could be
    avoided easily with a simple expression
  • ArrayIndexOutofBound - instead lengh property
    could be used
  • Do more testing rather than throwing exceptions

Exceptions take up a lot of processing time - use
them with care
44
Some Useful URLs
Error Handling in Java...
  • http//chortle.ccsu.ctstateu.edu/cs151/Notes/chap8
    1/ch81_2.html
  • Exception fundamentals
  • http//java.sun.com/docs/books/tutorial/essential/
    exceptions/definition.html
  • A list of exception types
  • http//java.sun.com/docs/books/tutorial/essential/
    exceptions/throwing.html
  • throws clause

45
IT1202 - Fundamentals Of ProgrammingError
Handling in Java
Write a Comment
User Comments (0)
About PowerShow.com