Exception Handling in Java

 
Module 5
 
Exception and
Exception Handling
 
O
v
e
r
v
i
e
w
 
What are exceptions and why are they needed?
New keywords and their structure
try
catch
finally
How to throw exceptions from methods
How to create your own exceptions
Checked vs. Unchecked exceptions
 
E
x
c
e
p
t
i
o
n
 
H
a
n
d
l
i
n
g
 
An exception is an indication of a potential
problem that occurs during a program’s
execution.
We can resolve these issues 
without crashing
We can develop more 
fault-tolerant
 programs.
Build 
more secure
 systems
Prior to exceptions being created:
Every function returned a value (even print!)
Had to check that value to see if it ran correctly
 
 
H
e
y
,
 
w
h
a
t
 
c
o
u
l
d
 
g
o
 
w
r
o
n
g
?
 
import
 java.util.*;
class
 Main {
  
public
 
static
 
void
 main(String[] args) {
    
int
 num1, num2, result;
    Scanner scan = 
new
 Scanner (System.in);
    System.out.print (
"Enter num1: "
);
    num1 = scan.nextInt();
    System.out.print (
"Enter num2: "
);
    num2 = scan.nextInt();
    result = num1/num2;
    System.out.println (
"Result: "
+result);
  }
}
 
H
e
y
,
 
w
h
a
t
 
c
o
u
l
d
 
g
o
 
w
r
o
n
g
?
 
import
 java.util.*;
class
 Main {
  
public
 
static
 
void
 main(String[] args) {
    
int
 num1, num2, result;
    Scanner scan = 
new
 Scanner (System.in);
    System.out.print (
"Enter num1: "
);
    num1 = scan.nextInt();
    System.out.print (
"Enter num2: "
);
    num2 = scan.nextInt();
    result = num1/num2; 
 // what if num2 is 0?
    System.out.println (
"Result: "
+result);
  }
}
 
S
e
c
u
r
i
t
y
 
I
s
s
u
e
s
?
 
I
f
 
s
o
,
 
w
h
e
r
e
?
 
import
 java.util.*;
class
 Main {
  
public
 
static
 
void
 main(String[] args) {
    
int
[] nums = 
new
 
int
[
50
];
    
int
 userInput;
    Scanner scan = 
new
 Scanner (System.in);
    System.out.print (
"Show which element? "
);
    userInput = scan.nextInt();
    System.out.println (nums[userInput]);
  }
}
 
S
e
c
u
r
i
t
y
 
I
s
s
u
e
s
?
 
I
f
 
s
o
,
 
w
h
e
r
e
?
 
import
 java.util.*;
class
 Main {
  
public
 
static
 
void
 main(String[] args) {
    
int
[] nums = 
new
 
int
[
50
];
    
int
 userInput;
    Scanner scan = 
new
 Scanner (System.in);
    System.out.print (
"Show which element? "
);
    userInput = scan.nextInt();
    System.out.println (nums[
userInput
]);
    
// What if userInput is 60?
  }
}
 
W
h
a
t
 
h
a
p
p
e
n
e
d
?
 
Do we always have a problem? NO.
Do we have the 
potential
 for a problem? YES
Example 1: potential to divide by zero
Example 2: potential to access memory outside the bounds of the
array
What could happen?
Example 1: a DivideByZeroException could be thrown
Example 2: an ArrayIndexOutOfBoundsException could be thrown
 
T
h
e
 
m
a
i
n
 
i
d
e
a
 
We are going to 
try
 to do some code
If something messes up, it creates an exception that we can
catch
.
The finally block runs whether an exception was thrown or not
 
    
try
 {
      
// Some potentially problematic code
    }
    
catch
 (Exception e) {
      
// Handle the problem, but DON'T CRASH
 
 // ’e’ is a variable that holds the exception
    }
    
finally
 {
      
// Optional.  This runs whether an
      
// exception was thrown or not
    }
 
E
x
c
e
p
t
i
o
n
 
H
i
e
r
a
r
c
h
y
 
i
n
 
J
a
v
a
 
 
E
x
c
e
p
t
i
o
n
 
H
i
e
r
a
r
c
h
y
 
i
n
 
C
#
 
 
T
h
e
 
F
l
o
w
 
o
f
 
E
x
c
e
p
t
i
o
n
 
H
a
n
d
l
i
n
g
 
When a “problem” occurs in a try block:
1.
A
n exception is thrown
2.
Program control 
immediately transfers
 to the first
catch block matching the type of the thrown
exception.
3.
After the exception is handled, program control
resumes after the last catch block.
 
 
T
h
e
 
F
l
o
w
 
o
f
 
E
x
c
e
p
t
i
o
n
 
H
a
n
d
l
i
n
g
 
When a problem DOES NOT occur in a try block:
1.
A
n exception is NOT thrown
2.
The catch block(s) do NOT execute at all
3.
Execution continues through the “try” block, then
continues after the catch/finally block
 
 
R
u
l
e
s
 
o
n
 
t
h
e
 
c
a
t
c
h
 
b
l
o
c
k
 
Must have one or more catches immediately after the
try block
Yes, you can have more than one catch block
Only one catch block executes – 
the first matching one
The order matters:
There’s an Exception hierarchy
Child class must appear before parent classes
Why?
Usually have the generic Exception as the last class
 
c
a
t
c
h
 
B
l
o
c
k
 
catch
(IO.FileNotFoundException fnfe)
{
   // handle file not found (using fnfe object)
}
catch
(Exception e)
{
   // handle other type of exception (using e object)
}
 
finally Block
 
This is the “cleanup” block
Example: Operating systems typically prevent
more than one program from manipulating a file.
Therefore, the program should 
close the file
(i.e., release the resource) 
whether an exception
was thrown or not
The finally block is 
guaranteed
 to execute
regardless of whether an exception occurs.
Note: the finally block can’t see variables
declared in the 
try
 or 
catch
 blocks
 
F
u
l
l
 
t
r
y
/
c
a
t
c
h
/
f
i
n
a
l
l
y
 
S
y
n
t
a
x
 
t
r
y
 
{
 
 
 
/
/
 
c
o
d
e
 
t
h
a
t
 
m
i
g
h
t
 
g
e
n
e
r
a
t
e
 
a
n
 
e
x
c
e
p
t
i
o
n
}
c
a
t
c
h
(
 
C
h
i
l
d
E
x
c
e
p
t
i
o
n
C
l
a
s
s
 
e
1
 
)
 
{
 
 
 
/
/
 
c
o
d
e
 
t
o
 
h
a
n
d
l
e
 
a
n
 
E
x
c
e
p
t
i
o
n
1
C
l
a
s
s
 
e
x
c
e
p
t
i
o
n
}
 
 
c
a
t
c
h
(
 
P
a
r
e
n
t
E
x
c
e
p
t
i
o
n
C
l
a
s
s
 
e
N
 
)
 
{
 
 
 
/
/
 
c
o
d
e
 
t
o
 
h
a
n
d
l
e
 
a
n
 
E
x
c
e
p
t
i
o
n
N
C
l
a
s
s
 
e
x
c
e
p
t
i
o
n
}
c
a
t
c
h
 
(
 
E
x
c
e
p
t
i
o
n
 
e
 
)
 
{
 
 
 
/
/
 
c
o
d
e
 
t
o
 
h
a
n
d
l
e
 
a
n
y
t
h
i
n
g
 
t
h
a
t
 
m
a
d
e
 
i
t
 
 
 
/
/
 
t
h
r
o
u
g
h
 
t
h
e
 
f
i
r
s
t
 
t
w
o
 
c
a
t
c
h
 
b
l
o
c
k
s
}
f
i
n
a
l
l
y
{
 
 
/
/
 
c
o
d
e
 
t
o
 
e
x
e
c
u
t
e
 
w
h
e
t
h
e
r
 
o
r
 
n
o
t
 
a
n
 
e
x
c
e
p
t
i
o
n
 
o
c
c
u
r
s
}
 
B
e
s
t
 
p
r
a
c
t
i
c
e
 
Do not place try blocks around 
every
 statement that might
throw an exception.
 
It’s better to place 
one try block around a significant portion
of code and follow this try block with catch blocks that
handle each possible exception.
 
Separate try blocks 
should
 be used when it is important to
distinguish between multiple statements that can throw the
same exception type.
 
P
a
r
t
 
2
:
 
T
h
r
o
w
i
n
g
 
E
x
c
e
p
t
i
o
n
s
 
Inside a method, you can throw 
any kind 
of exception
you want, at 
any time
 you want:
 
throw new
 Exception(); // OR
throw new
 FileIOException();
 
However, Java and C# syntax slightly differ
 
E
x
a
m
p
l
e
 
o
f
 
T
h
r
o
w
i
n
g
 
i
n
 
C
#
 
-
 
N
o
 
C
r
a
s
h
 
using
 
System
;
class
 Example {
  
public
 
static
 
void
 doStuff ()  {
    
throw
 
new
 Exception(
"CSE 1322"
);
  }
  
public
 
static
 
void
 Main(String[] args) {
    
try
 {
      doStuff();  
// This throws an exception
      Console.WriteLine(
"This line never prints"
);
    }
catch
 (Exception e) {
      
// This prints “Exception thrown: CSE 132
2
      Console.WriteLine(
"Exception thrown: "
+e.Message);
    }
    
finally
 {
      Console.WriteLine(
"This prints no matter what"
);
    }
  }
}
 
A
n
o
t
h
e
r
 
i
n
 
C
#
 
-
 
I
n
s
t
a
n
t
 
C
r
a
s
h
 
using
 
System
;
class
 Example {
  
public
 
static
 
void
 doStuff ()  {
    
throw
 
new
 Exception();
  }
  
public
 
static
 
void
 Main(String[] args) {
    doStuff();  
// Crashes the program
  }
}
 
T
h
r
o
w
i
n
g
 
E
x
c
e
p
t
i
o
n
s
 
i
n
 
J
a
v
a
 
The 
throw
 keyword works the same as C#
In Java, must also use the 
throws
 keyword
Method states what kind of exception(s) it is throwing
Multiple exception types are separated by a comma
You must know the difference between the keywords
throw
 and 
throws
Common interview question
 
Best shown through example
 
E
x
a
m
p
l
e
 
o
f
 
T
h
r
o
w
/
T
h
r
o
w
s
 
i
n
 
J
a
v
a
 
class
 Main {
  
public
 
static
 
void
 doStuff() 
throws
 Exception {
    
throw
 
new
 Exception(
"CSE 1322"
);
  }
  
public
 
static
 
void
 main(String[] args) {
    
try
 {
      doStuff();  
// This throws an exception
      System.out.println(
"This line never prints"
);
    }
catch
 (Exception e) {
      System.out.println(
"Exception thrown: "
+e);
    }
    
finally
 {
      System.out.println(
"This prints no matter what"
);
    }
  }
}
 
E
x
a
m
p
l
e
 
i
n
 
J
a
v
a
 
 
C
o
m
p
i
l
e
 
t
i
m
e
 
e
r
r
o
r
 
class
 Main {
  
public
 
static
 
void
 doStuff() 
throws
 Exception {
    
throw
 
new
 Exception(
"CSE 1322"
);
  }
  
public
 
static
 
void
 main(String[] args) {
    
// The compiler knows this method throws
    // an exception, so it forces you to use
    // a try/catch
    doStuff();
  }
}
 
M
o
r
e
 
J
a
v
a
 
I
n
t
e
r
v
i
e
w
 
A
d
v
i
c
e
 
Interviewers also ask the difference
between final, finally, and finalize
final – a keyword you can put in front of a
method and attribute
finally – part of the exception handling flow of
control
finalize( ) – a method that you inherit from the
Object class, used for cleanup.  Also be called
a “destructor”, the opposite of a “constructor”
 
P
a
r
t
 
3
:
 
C
r
e
a
t
i
n
g
 
y
o
u
r
 
o
w
n
 
E
x
c
e
p
t
i
o
n
s
 
Why?
Example: building the software for a car
May want to create a CarNotStartedException
How: create a class that inherits from Exception
Include a default constructor
Include an overloaded constructor that takes in a
string
 
D
e
s
i
g
n
i
n
g
 
Y
o
u
r
 
O
w
n
 
E
x
c
e
p
t
i
o
n
 
T
y
p
e
s
 
class
 InsufficientFundsException 
extends
 Exception
{
  
public
 InsufficientFundsException() {}
  
public
 InsufficientFundsException(String message)
  {
    
super
(message);
  }
}
 
D
e
s
i
g
n
i
n
g
 
Y
o
u
r
 
O
w
n
 
E
x
c
e
p
t
i
o
n
 
T
y
p
e
s
 
class
 InsufficientFundsException : Exception
{
  
public
 InsufficientFundsException() {}
  
public
 InsufficientFundsException(String message)
    :
base
(message)
  {
  }
}
 
C
h
e
c
k
e
d
 
a
n
d
 
U
n
c
h
e
c
k
e
d
 
E
x
c
e
p
t
i
o
n
s
 
Java distinguishes between 
two types
 of exceptions:
 
U
n
c
h
e
c
k
e
d
 
e
x
c
e
p
t
i
o
n
s
Inherit from of 
Error
 or 
RuntimeException
Not mandatory to use 
try
 and 
catch
 blocks to handle these exceptions.
Not checked by the compiler at Compile Time
Example: divide by zero
Checked exceptions
Inherit from Exception
Must be put inside a 
try
 block or the method must acknowledge that
the exception may occur by using a 
throws 
clause in the method
header.
Checked by the compiler at compile time
 
C
h
e
c
k
e
d
 
v
s
 
U
n
c
h
e
c
k
e
d
 
E
x
c
e
p
t
i
o
n
s
 
W
h
a
t
 
k
i
n
d
 
o
f
 
E
x
c
e
p
t
i
o
n
?
 
W
h
a
t
 
k
i
n
d
 
o
f
 
E
x
c
e
p
t
i
o
n
?
 
C
h
e
c
k
e
d
 
a
n
d
 
U
n
c
h
e
c
k
e
d
 
E
x
c
e
p
t
i
o
n
s
 
C# provides checked and unchecked keywords to
handle integral type exceptions.
Checked means to throw an exception if there’s an
arithmetic error
Unchecked means to ignore the exception if it’s thrown
 
More at:
https://docs.microsoft.com/en-us/dotnet/csharp/language-
reference/keywords/checked
 
https://
www.javatpoint.com/c-sharp-checked-and-unchecked
 
E
x
a
m
p
l
e
 
using
 
System
;
 
class
 Example {
  
public
 
static
 
void
 Main(String[] args) {
    
int
 value = 
2147483647
;
    
int
 result = value + 
10
;
    
// prints -2147483639
    Console.WriteLine (result);
  }
}
 
E
x
a
m
p
l
e
 
 
u
s
i
n
g
 
c
h
e
c
k
e
d
 
using
 
System
;
class
 Example {
  
public
 
static
 
void
 Main(String[] args) {
    
int
 value = 
2147483647
;
    
// This now throws an OverflowException
    
int
 result = 
checked
(value + 
10
);
    Console.WriteLine (result);
  }
}
 
S
u
m
m
a
r
y
 
Using exceptions helps with building robust, secure code
Uses keywords 
try
, 
catch
 and 
finally
You can throw exceptions in methods
You can create your own exceptions by inheriting from an
existing exception class
Java makes extensive use of checked and unchecked
exceptions
Slide Note
Embed
Share

Exception handling in Java is essential for dealing with potential problems that may arise during program execution. By implementing try-catch-finally blocks and throwing custom exceptions, developers can create more robust and secure applications. This article explores the basics of exceptions, the differences between checked and unchecked exceptions, and how to handle common issues like division by zero and array index out of bounds.

  • - Exception handling - Java programming - Error handling - Fault tolerance - Custom exceptions

Uploaded on Sep 22, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Module 5 Exception and Exception Handling

  2. Overview What are exceptions and why are they needed? New keywords and their structure try catch finally How to throw exceptions from methods How to create your own exceptions Checked vs. Unchecked exceptions

  3. Exception Handling An exception is an indication of a potential problem that occurs during a program s execution. We can resolve these issues without crashing We can develop more fault-tolerant programs. Build more secure systems Prior to exceptions being created: Every function returned a value (even print!) Had to check that value to see if it ran correctly

  4. Hey, what could go wrong? import java.util.*; class Main { public static void main(String[] args) { int num1, num2, result; Scanner scan = new Scanner (System.in); System.out.print ("Enter num1: "); num1 = scan.nextInt(); System.out.print ("Enter num2: "); num2 = scan.nextInt(); result = num1/num2; System.out.println ("Result: "+result); } }

  5. Hey, what could go wrong? import java.util.*; class Main { public static void main(String[] args) { int num1, num2, result; Scanner scan = new Scanner (System.in); System.out.print ("Enter num1: "); num1 = scan.nextInt(); System.out.print ("Enter num2: "); num2 = scan.nextInt(); result = num1/num2; // what if num2 is 0? System.out.println ("Result: "+result); } }

  6. Security Issues? If so, where? import java.util.*; class Main { public static void main(String[] args) { int[] nums = new int[50]; int userInput; Scanner scan = new Scanner (System.in); System.out.print ("Show which element? "); userInput = scan.nextInt(); System.out.println (nums[userInput]); } }

  7. Security Issues? If so, where? import java.util.*; class Main { public static void main(String[] args) { int[] nums = new int[50]; int userInput; Scanner scan = new Scanner (System.in); System.out.print ("Show which element? "); userInput = scan.nextInt(); System.out.println (nums[userInput]); // What if userInput is 60? } }

  8. What happened? Do we always have a problem? NO. Do we have the potential for a problem? YES Example 1: potential to divide by zero Example 2: potential to access memory outside the bounds of the array What could happen? Example 1: a DivideByZeroException could be thrown Example 2: an ArrayIndexOutOfBoundsException could be thrown

  9. The main idea We are going to try to do some code If something messes up, it creates an exception that we can catch. The finally block runs whether an exception was thrown or not try { // Some potentially problematic code } catch (Exception e) { // Handle the problem, but DON'T CRASH // e is a variable that holds the exception } finally { // Optional. This runs whether an // exception was thrown or not }

  10. Exception Hierarchy in Java

  11. Exception Hierarchy in C#

  12. The Flow of Exception Handling When a problem occurs in a try block: 1. An exception is thrown 2. Program control immediately transfers to the first catch block matching the type of the thrown exception. 3. After the exception is handled, program control resumes after the last catch block.

  13. The Flow of Exception Handling When a problem DOES NOT occur in a try block: 1. An exception is NOT thrown 2. The catch block(s) do NOT execute at all 3. Execution continues through the try block, then continues after the catch/finally block

  14. Rules on the catch block Must have one or more catches immediately after the try block Yes, you can have more than one catch block Only one catch block executes the first matching one The order matters: There s an Exception hierarchy Child class must appear before parent classes Why? Usually have the generic Exception as the last class

  15. catch Block catch(IO.FileNotFoundException fnfe) { // handle file not found (using fnfe object) } catch(Exception e) { // handle other type of exception (using e object) }

  16. finally Block This is the cleanup block Example: Operating systems typically prevent more than one program from manipulating a file. Therefore, the program should close the file (i.e., release the resource) whether an exception was thrown or not The finally block is guaranteed to execute regardless of whether an exception occurs. Note: the finally block can t see variables declared in the try or catch blocks

  17. Full try/catch/finally Syntax try { // code that might generate an exception } catch( ChildExceptionClass e1 ) { // code to handle an Exception1Class exception } catch( ParentExceptionClass eN ) { // code to handle an ExceptionNClass exception } catch ( Exception e ) { // code to handle anything that made it // through the first two catch blocks } finally { // code to execute whether or not an exception occurs }

  18. Best practice Do not place try blocks around every statement that might throw an exception. It s better to place one try block around a significant portion of code and follow this try block with catch blocks that handle each possible exception. Separate try blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type.

  19. Part 2: Throwing Exceptions Inside a method, you can throw any kind of exception you want, at any time you want: throw new Exception(); // OR throw new FileIOException(); However, Java and C# syntax slightly differ

  20. Example of Throwing in C# - No Crash using System; class Example { public static void doStuff () { throw new Exception("CSE 1322"); } public static void Main(String[] args) { try { doStuff(); // This throws an exception Console.WriteLine("This line never prints"); }catch (Exception e) { // This prints Exception thrown: CSE 1322 Console.WriteLine("Exception thrown: "+e.Message); } finally { Console.WriteLine("This prints no matter what"); } } }

  21. Another in C# - Instant Crash using System; class Example { public static void doStuff () { throw new Exception(); } public static void Main(String[] args) { doStuff(); // Crashes the program } }

  22. Throwing Exceptions in Java The throw keyword works the same as C# In Java, must also use the throws keyword Method states what kind of exception(s) it is throwing Multiple exception types are separated by a comma You must know the difference between the keywords throw and throws Common interview question Best shown through example

  23. Example of Throw/Throws in Java class Main { public static void doStuff() throws Exception { throw new Exception("CSE 1322"); } public static void main(String[] args) { try { doStuff(); // This throws an exception System.out.println("This line never prints"); }catch (Exception e) { System.out.println("Exception thrown: "+e); } finally { System.out.println("This prints no matter what"); } } }

  24. Example in Java Compile time error class Main { public static void doStuff() throws Exception { throw new Exception("CSE 1322"); } public static void main(String[] args) { // The compiler knows this method throws // an exception, so it forces you to use // a try/catch doStuff(); } }

  25. More Java Interview Advice Interviewers also ask the difference between final, finally, and finalize final a keyword you can put in front of a method and attribute finally part of the exception handling flow of control finalize( ) a method that you inherit from the Object class, used for cleanup. Also be called a destructor , the opposite of a constructor

  26. Part 3: Creating your own Exceptions Why? Example: building the software for a car May want to create a CarNotStartedException How: create a class that inherits from Exception Include a default constructor Include an overloaded constructor that takes in a string

  27. Designing Your Own Exception Types class InsufficientFundsException extends Exception { public InsufficientFundsException() {} public InsufficientFundsException(String message) { super(message); } }

  28. Designing Your Own Exception Types class InsufficientFundsException : Exception { public InsufficientFundsException() {} public InsufficientFundsException(String message) :base(message) { } }

  29. Checked and Unchecked Exceptions Java distinguishes between two types of exceptions: Unchecked exceptions Inherit from of Error or RuntimeException Not mandatory to use try and catch blocks to handle these exceptions. Not checked by the compiler at Compile Time Example: divide by zero Checked exceptions Inherit from Exception Must be put inside a try block or the method must acknowledge that the exception may occur by using a throws clause in the method header. Checked by the compiler at compile time

  30. Checked vs Unchecked Exceptions

  31. What kind of Exception?

  32. What kind of Exception?

  33. Checked and Unchecked Exceptions C# provides checked and unchecked keywords to handle integral type exceptions. Checked means to throw an exception if there s an arithmetic error Unchecked means to ignore the exception if it s thrown More at: https://docs.microsoft.com/en-us/dotnet/csharp/language- reference/keywords/checked https://www.javatpoint.com/c-sharp-checked-and-unchecked

  34. Example using System; class Example { public static void Main(String[] args) { int value = 2147483647; int result = value + 10; // prints -2147483639 Console.WriteLine (result); } }

  35. Example using checked using System; class Example { public static void Main(String[] args) { int value = 2147483647; // This now throws an OverflowException int result = checked(value + 10); Console.WriteLine (result); } }

  36. Summary Using exceptions helps with building robust, secure code Uses keywords try, catch and finally You can throw exceptions in methods You can create your own exceptions by inheriting from an existing exception class Java makes extensive use of checked and unchecked exceptions

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#