Title: Exceptions
1Exceptions
2Overview
- Definition of exceptions
- The history behind exceptions
- When exceptions occur
- How to handle exceptions
- Throwing exceptions
- Creating your own exceptions
3History
- The language C has returns codes
- if (someFunction( ) 0)
- else if (someFunction( ) -1)
- Burden on programmer
- Memorize what all the return codes meant
- Had to wrap each function call in an if statement
- Sloppy coders didnt check return codes (crash)
4Along come Exceptions
- An exception is an unusual circumstance
- Usually associated with something gone wrong
- Doesnt have to be
- Idea Some methods could possibly throw one of
these exceptions - You need to try to do the method
- If exception is thrown, you need to catch it
5Introduction
- Exception
- Indication of problem during programs execution
- Although problem can occur, it occurs
infrequently
6Introduction
- Exception handling
- Clear, robust and more fault-tolerant programs
- Continue normal execution
- Sever problems
- Prevent normal execution
- Notification
- Termination
7Exception Handling Overview
- Program detects error
- Throws exception (throw point)
- Caught by exception handler
- Handled
- Uncaught (no appropriate exception handler)
- Debug mode
- Ignore, continue execution
- View in debugger
- Standard execution mode
- Ignore, continue execution
- Terminate
8 Exception Handling Overview
- Try block
- Encloses code in which errors may occur
9Exception Handling Overview
- Catch block (Catch handler)
- Appears after Try block
- Parameter included
- Handles specific exception type
- Parameterless
- Handles all exception types
10Exception Handling Overview
- Finally block
- Appears after last Catch handler
- Optional (if one or more catch handlers exist)
- Encloses code that always executes
11.NET Exception Hierarchy
- Class Exception
- Base class of .NET Framework exception hierarchy
- Important classes derived from Exception
- ApplicationException
- Can create exception data types specific to
applications - SystemException
- Runtime exceptions
- Can occur anytime during execution
- Avoid with proper coding
12.NET Exception Hierarchy
- Benefit of hierarchy
- Inheritance
- If handling behavior same for base and derived
classes - Able to catch base class
- Otherwise catch derived classes individually
- Ex.
- Catch handler with parameter type Exception
- Able to catch all exceptions
13Exception Properties
- Property Message
- Stores exception objects error message
- Default message
- Associated with exception type
- Customized message
- Passed to exception objects constructor
14Finally Block
- Encloses code that always executes
- Code executes whether exception occurs or not
- Optional
- Not required if one or more catch handlers exist
- Why use Finally block?
- Typically releases resources acquired in Try
block - Helps eliminate resource leaks
15Java Example
- There is a Thread class, with the method
- public void sleep (long milliseconds) throws
InterruptedException - Notice it says throws InterruptedException
- It could possibly throw one
- We must handle this method call with care
- Usage
- Thread.sleep (5000) // Ask to pause for 5
seconds
16Something That Wont Work
- class Driver
- public static void main (String args )
- System.out.println (I am sleeping)
- Thread.sleep (5000)
- System.out.println (I am awake)
- // end main
- // end Driver
- Compile error sleep must be placed in a
try/catch block
17Introducing the try/catch block
- class Driver
- public static void main (String args )
- System.out.println (I am sleeping)
- try
- Thread.sleep (5000)
- System.out.println (Yawn)
-
- catch (InterruptedException e)
- System.out.println (An error occurred)
-
- System.out.println (I am awake)
- // end main
- // end Driver
18Introducing the try/catch block
- class Driver
- public static void main (String args )
- System.out.println (I am sleeping)
- try
- Thread.sleep (5000)
- System.out.println (Yawn)
-
- catch (InterruptedException e)
- System.out.println (An error occurred)
-
- System.out.println (I am awake)
- // end main
- // end Driver
This is what could throw the exception
19Logic(if exception is not thrown)
- class Driver
- public static void main (String args )
- System.out.println (I am sleeping)
- try
- Thread.sleep (5000)
- System.out.println (Yawn)
-
- catch (InterruptedException e)
- System.out.println (An error occurred)
-
- System.out.println (I am awake)
- // end main
- // end Driver
If things run the way they should, output is I
am sleeping Yawn I am awake
20Logic(if exception is thrown)
- class Driver
- public static void main (String args )
- System.out.println (I am sleeping)
- try
- Thread.sleep (5000)
- System.out.println (Yawn)
-
- catch (InterruptedException e)
- System.out.println (An error occurred)
-
- System.out.println (I am awake)
- // end main
- // end Driver
If things run the way they should, output is I
am sleeping An error occurred I am awake
21Rules
- When the exception was thrown, we handled it in
the catch section - The program continues to execute
- To terminate the program, use
- System.exit (1)
- The Exception class is the parent of all
exceptions - You can have multiple catch blocks to catch
specific types of exceptions - Make sure you put most general at bottom
22Example
- class Driver
- public static void main (String args )
- try
- // a lot of code that could throw
- // several different kinds of exceptions
-
- catch (NullPointerException e)
- catch (InterruptedException e)
- catch (Exception e)
-
23The finally clause
- Finally works with try and catch
- Comes after the try/catch
- It executes whether an exception was thrown or
not - System.exit ( ) is the only way it wont execute
24Example(Finally prints no matter what)
- class Driver
- public static void main (String args )
- try
- Thread.sleep (1000)
- System.out.println (Yawn)
-
- catch (Exception e)
- finally
- System.out.println (Finally!)
- // finally
- // main
- // driver
25Example(Finally wont print if exception is
thrown)
- class Driver
- public static void main (String args )
- try
- Thread.sleep (1000)
- System.out.println (Yawn)
-
- catch (Exception e) System.exit (0)
- finally
- System.out.println (Finally!)
- // finally
- // main
- // driver
26VB Example
- Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click - Dim intx, inty, result As Integer
- inty 0
- intx 5
- Try
- intx TextBox1.Text
- result intx \ inty
- Catch ex As DivideByZeroException
- MessageBox.Show(ex.Message)
- Catch ex1 As Exception
- MessageBox.Show(ex1.Message)
- Finally
- MessageBox.Show("End of Proc")
- End Try
- End Sub
27C Example
- private void button1_Click(object sender,
System.EventArgs e) -
- int a, b, c
-
- b 0
- try
-
- a Int32.Parse(textBox1.Text)
- c a / b
-
-
- catch(DivideByZeroException ex)
-
- MessageBox.Show(ex.Message,"Divide by Zero")
-
- catch(Exception ex)
-
- MessageBox.Show(ex.Message)
-
28Creating Your Own Exception
- class SleepException extends Exception
- SleepException ( )
- super ( ) // Call the superclass constructor
-
- SleepException (String s)
- super ( s ) // Call the superclass
constructor -
-
- // Remember, Exception is the parent class of
- // exceptions
29Getting JavaDog to sleep
- We can define a sleep function in JavaDog
- Throws our new SleepException
- When we tell JavaDog to sleep( ), it will need to
be in a try/catch block
30JavaDog sleeps!
Can throw any kind of Exception
- class JavaDog
- // Constructor and other methods
- void sleep (long amountOfSleep) throws
Exception - if (amountOfSleep lt 0)
- throw (new SleepException( ) )
- else
- Thread.sleep (amountOfSleep)
- // sleep
- // JavaDog
31JavaDog sleeps!
- class DogDriver
- public static void main (String args )
- JavaDog j1 new JavaDog (14, bob)
- try
- j1.sleep (4000)
-
- catch (SleepException e)
- System.out.println (SleepException occured)
-
- catch (InterruptedException e)
- System.out.println (InterruptedException)
-
- finally
- System.out.println (Wake up!)
- // finally
- // main
- // DogDriver
32VB-Create Own Exception Class
- Dim intx, inty, result As Integer
- inty 0
- intx 5
- Try
- intx TextBox1.Text
- If intx lt 0 Then
- Throw New ExceptClass("Number not
Allowed", intx) - End If
- If intx gt 10 Then
- Throw New ExceptClass
- End If
- Catch ex As DivideByZeroException
- MessageBox.Show(ex.Message)
- Catch ex1 As Exception
33C-Create own Exception Class
- private void button1_Click(object sender,
System.EventArgs e) -
- int a, b, c
- b 0
- try
- a Int32.Parse(textBox1.Text)
- if( a lt 0)
- throw new ExceptionClass()
- if (a gt 10)
- throw new ExceptionClass("Out of
Range") - c a / b
-
- catch(DivideByZeroException ex)
-
- MessageBox.Show(ex.Message,"Divide by Zero")
-
- catch(Exception ex)
-
- MessageBox.Show(ex.Message)
34Summary
- Exceptions are used to handle errors
- Keywords try, catch, finally, throw, throws
- You try to do a method that could throw an
exception - Catch will handle the exception (if thrown)
- Method are the ones who throw the exceptions
- You can easily create your own exceptions
- System.exit ( ) terminates the program