Exception Handling Chapter 12 from Visual C - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Exception Handling Chapter 12 from Visual C

Description:

Unchecked Exceptions. Creating Custom Exceptions. What is an Exception? An exception is an event that occurs during the execution (Run Time) of a ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 35
Provided by: beiz
Category:

less

Transcript and Presenter's Notes

Title: Exception Handling Chapter 12 from Visual C


1
Exception Handling Chapter 12 fromVisual C
2005 How to Program, Deitel Deitel
2
Exceptions
  • What is exceptions
  • Catching and Handling Exceptions
  • How to Throw Exceptions
  • Unchecked Exceptions
  • Creating Custom Exceptions

3
What is an Exception?
  • An exception is an event that occurs during the
    execution (Run Time) of a program that disrupts
    the normal flow of instructions.

4
Three Exceptions Example
  • int x5
  • int y0
  • int zx/y
  • int.Parse(hello)
  • public void SomeMethod(...)
  • File file new File("Readme.txt")
  • .
  • .
  • .
  • file.Close()

Divide by zero
Convert hello into int!
The file doesnt exist.
BIG QUESTION. What will happen then?
5
Program Normal Flow, No Exception
  • static void Main()
  • // get numerator and denominator
  • Console.Write("Please enter an integer
    numerator ")
  • int numerator int.Parse(Console.ReadLine())
  • Console.Write("Please enter an integer
    denominator ")
  • int denominator int.Parse(Console.ReadLine()
    )
  • // divide the two integers, then display the
    result
  • int result divide(numerator, denominator)
  • Console.WriteLine("\nResult " numerator
    " / "
  • denominator " " result)
  • Console.WriteLine("End of the program")
  • // end Main

1
2
3
4
6
static int divide(int value1, int value2)
int result value1 / value2 return result
5,9
10
7
8
11
6
Program Flow with Unhandled Exception
  • static void Main()
  • // get numerator and denominator
  • Console.Write("Please enter an integer
    numerator ")
  • int numerator int.Parse(Console.ReadLine())
  • Console.Write("Please enter an integer
    denominator ")
  • int denominator int.Parse(Console.ReadLine()
    )
  • // divide the two integers, then display the
    result
  • int result divide(numerator, denominator)
  • Console.WriteLine("\nResult " numerator
    " / "
  • denominator " " result)
  • Console.WriteLine("End of the program")
  • // end Main

1
2
3
4
6
static int divide(int value1, int value2)
int result value1 / value2 return result
5
7
Exit the program
7
Program Flow with Unhandled Exception (2)
  • static void Main()
  • // get numerator and denominator
  • Console.Write("Please enter an integer
    numerator ")
  • int numerator int.Parse(Console.ReadLine())
  • Console.Write("Please enter an integer
    denominator ")
  • int denominator int.Parse(Console.ReadLine()
    )
  • // divide the two integers, then display the
    result
  • int result divide(numerator, denominator)
  • Console.WriteLine("\nResult " numerator
    " / "
  • denominator " " result)
  • Console.WriteLine("End of the program")
  • // end Main

1
2
3
5 int.Parse method
4
static int divide(int value1, int value2)
int result value1 / value2 return result
Exit the program
8
Exception generation
  • Exception generated with keyword throw
  • must create and throw exception object
  • can generated by user code, CLR, or .NET Framework

int Divide(int n, int d) if (d 0)
throw new DivideByZeroException("divide by
zero") return n / d
user code
int data ... dataindex 17
CLR
FileStream f new FileStream("MyFile.dat",
FileMode.Open)
Framework
9
Information Included in the Exception
  • The code location
  • The type
  • The reason (message)
  • Stack Trace

10
Catching and Handling Exceptions
  • Code that may generate exception is placed inside
    try block.
  • Directly followed by one or more catch blocks.
  • One optional finally block can be followed by
    catch blocks.
  • Each catch block includes a type filter that
    determines the types of exceptions it handles.
  • If try block catches an exception it will handle
    it with the first matching catch block and skip
    the rest catch block.
  • If not match, the exception is not handled.
  • Code in finally block got always executed.

11
DivideByZeroTest.cs
  • static void Main()
  • try
  • // get numerator and denominator
  • Console.Write("Please enter an integer
    numerator ")
  • int numerator int.Parse(Console.ReadLine
    ())
  • Console.Write("Please enter an integer
    denominator ")
  • int denominator int.Parse(Console.ReadLi
    ne())
  • // divide the two integers, then display
    the result
  • int result divide(numerator,
    denominator)
  • Console.WriteLine("\nResult "
    numerator " / " denominator " "
    result)
  • catch (FormatException)
  • Console.WriteLine("You must enter two
    integers.",
  • "Invalid Number Format")

1
2
3
4
6
5
7
8
9
Program Ends Normally
12
DivideByZeroTest.cs
  • static void Main()
  • try
  • // get numerator and denominator
  • Console.Write("Please enter an integer
    numerator ")
  • int numerator int.Parse(Console.ReadLine
    ())
  • Console.Write("Please enter an integer
    denominator ")
  • int denominator int.Parse(Console.ReadLi
    ne())
  • // divide the two integers, then display
    the result
  • int result divide(numerator,
    denominator)
  • Console.WriteLine("\nResult "
    numerator " / " denominator " "
    result)
  • catch (FormatException)
  • Console.WriteLine("You must enter two
    integers.",
  • "Invalid Number Format")

1
2
3
4
6
5
7
8
9
10
11
12
Program Ends Normally
13
Try-catch-finally syntax
  • try
  • //code that may cause exception
  • catch(Exception var)
  • catch(Exception var)
  • ..more catch blocks
  • finally()
  • ..//this code will always occur

Must be derived from System.Exception
Optional
You may list more than on Catch block
OptionalFinally block always got executed
14
Part of the exception hierarchy
15
Throw and Re-Throw Exceptions
  • In general you may raise exception
  • throw new DivideByZeroException("Custom
    Message")
  • The above statement raises DivideByZeroException
    with a Custom Message.
  • throw can be use to rethrow a caught exception in
    try block
  • try
  • ..
  • catch(Exception ex)
  • throw//this will raise the Exception again.

16
Exceptions the general idea
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

17
  • try
  • some code that might throw an exception
  • more code
    No exception thrown
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

18
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • catch (any exception)
  • handle the exception
  • finally

19
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • return
  • catch (any exception)
  • handle the exception
  • finally

20
  • try
  • some code that might throw an exception
  • more code
  • catch (most specific exception)
  • handle the exception
  • catch (less specific exception)
  • This exception thrown
  • handle the exception
  • throw
  • catch (any exception)
  • handle the exception
  • finally

21
Handling ExceptionsAdvantages and Disadvantages
  • Advantage
  • Better usability
  • Close resources
  • Disadvantage
  • Performance Overhead

22
  • How do you Determine Which Exceptions a Method
    Throws?

23
(No Transcript)
24
12.7 Exception Properties
  • Properties for a caught exception
  • Message
  • Stores the error message associated with an
    Exception object
  • May be a default message or customized
  • StackTrace
  • Contain a string that represents the method call
    stack
  • Represent sequential list of methods that were
    not fully processed when the exception occurred
  • The exact location is called the throw point

25
exceptiondemo.cs
  • class ExceptionDemo
  • static void Main()
  • // call Method1 any Exception generated
    is caught
  • // in the catch block that follows
  • try
  • Method1()
  • // end try
  • catch (Exception exceptionParameter)
  • // output the string representation
    of the Exception, then output
  • // properties InnerException, Message
    and StackTrace
  • Console.WriteLine("exceptionParameter.
    ToString \n0\n",
  • exceptionParameter.ToString())
  • Console.WriteLine("exceptionParameter.
    Message \n0\n",
  • exceptionParameter.Message)
  • Console.WriteLine("exceptionParameter.
    StackTrace \n0\n",

26
  • // calls Method2
  • static void Method1()
  • try
  • Method2()
  • catch (Exception)
  • throw
  • // end method Method1
  • // throws an Exception containing an
    InnerException
  • static void Method2()
  • // attempt to convert string to int
  • try

27
exceptiondemo.cs (output)
28
12.8 Programmer-Defined Exception Classes
  • Creating customized exception types
  • Should derive from class ApplicationException.
    You may derive from Exception class (but not
    recommended)
  • Should end with Exception
  • Should define three constructors
  • A default constructor
  • A constructor that receives a string argument
  • A constructor that takes a string argument and an
    Exception argument
  • The Should is just best-practice.

29
12.8 Programmer-Defined Exception ClassesDesign
Considerations
  • When designing the Custom Exception class
  • Name of the exception
  • Default message (default constructor)
  • Freedom of choice, how many constructor. Usually
    implement the three (mentioned in the previous
    slide)
  • When using the Custom Exception class
  • When you will raise the exception. Make sure all
    cases are covered.
  • Use the right constructor and pass enough
    information.

30
Square Class
  • public class Square
  • private int side_length // A Field
  • public int Side_length // A Property
  • get return side_length
  • set
  • side_length value
  • public int area() // A Method
  • return (side_length side_length)
  • public Square(int side) // The Constructor
    method
  • side_length side

31
NegativeNumberException
  • using System
  • public class NegativeNumberException
    ApplicationException
  • // default constructor
  • public NegativeNumberException()
  • base("Illegal operation for a negative
    number")
  • // empty body
  • // end default constructor
  • // constructor for customizing error message
  • public NegativeNumberException(string
    messageValue)
  • base(messageValue)
  • // empty body
  • // end one-argument constructor
  • // constructor for customizing the
    exception's error
  • // message and specifying the InnerException
    object

32
Square Class (ver. 2)
  • public class Square
  • private int side_length // A Field
  • public int Side_length // A Property
  • get return side_length
  • set
  • if (value lt 0)
  • throw new NegativeNumberException(
  • "Square root of negative
    number not permitted")
  • else
  • side_length value
  • public int area() // A Method
  • return (side_length side_length)

33
SquareTest.cs
  • class SquareTest
  • static void Main()
  • string mySide System.Console.ReadLine()
  • int mySideInt int.Parse(mySide)
  • Square sq new Square(mySideInt)
  • int x sq.Side_length
  • // Retrieve objects Side_Length
    Property
  • sq.Side_length -15
  • // Change objects Side_length
    Property
  • int sq_area sq.area()
  • System.Console.WriteLine("Area "
    sq_area.ToString())

34
Finally Remember
  • In a catch block, you can
  • Rethrow the same exception, notifying code higher
    in the call stack
  • Throw a different exception, giving additional
    information to code higher in the call stack
  • Handle the exception and fall out the bottom of
    the catch block
  • Remember that
  • There is a performance hit for exceptions
Write a Comment
User Comments (0)
About PowerShow.com