0% found this document useful (0 votes)
3 views37 pages

Java Exception Handling Explained

This lecture covers advanced object-oriented programming concepts in Java, focusing on exception handling. It explains the types of programming errors (syntax, logic, and runtime), the nature of exceptions, and the difference between checked and unchecked exceptions. The document also details how to handle exceptions using try, catch, and finally blocks, along with examples demonstrating their implementation.

Uploaded by

natolef206
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Java Exception Handling Explained

This lecture covers advanced object-oriented programming concepts in Java, focusing on exception handling. It explains the types of programming errors (syntax, logic, and runtime), the nature of exceptions, and the difference between checked and unchecked exceptions. The document also details how to handle exceptions using try, catch, and finally blocks, along with examples demonstrating their implementation.

Uploaded by

natolef206
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOP Advanced in Java

Lecture 02

Samiullah Noori
Intro to Exceptions
Types of Programming Errors
 Three types of error:
 Syntax Errors – arise because the rules of the language are not followed.
 Logic Errors – arise because the program does perform the way it was intended to.

 Runtime Errors – arise because the program tries to perform an operation that is
impossible to carry out.

 Syntax errors are caught by the compiler, and fixed before the program is run.

 Logic Errors are detected by testing, and are fixed through debugging.

 Runtime Errors cause Exceptions and may be handled at runtime.


Exceptions
 An exception is an event that describes an unusual or erroneous
situation at runtime.

 Exceptions are wrapped up as objects

 A program can deal with an exception in one of three ways:

 ignore it
 handle it where it occurs
 handle it an another place in the program

 An error is also represented as an object in Java, but usually represents


an unrecoverable situation and should not be caught
Why Use Exceptions?
 Uses of exception handling
 Process exceptions from program components
 Handle exceptions in a uniform manner in large
projects
 Remove error-handling code from “main line” of
execution

 What if Exception is not handled?


 Might terminate program execution
Exceptions Types
 Two Types
 Unchecked
 Subclasses of RuntimeException and Error.
 Does not require explicit handling
 Run-time errors are internal to your program, so
you can get rid of them by debugging your code
 For example, null pointer exception; index out of
bounds exception; division by zero exception; ...
Exceptions Types
 Two Types
 Checked
 Must be caught or declared in a throws clause
 Compile will issue an error if not handled
appropriately
 Subclasses of Exception other than subclasses of
RuntimeException.
 Other arrive from external factors, and cannot be
solved by debugging
 Communication from an external resource – e.g. a
file server or database
Checked Exceptions
Throwable UnChecked Exceptions
Error

Exception Error

Runtime OutOf
IOException AWTError ThreadDeath
Exception MemoryError

ArrayIndexOutOfBoundsException InputMismatchException

ClassCastException NullPointerException ArithmeticException


How are
Java Exceptions Handled

?
How are Java exceptions handled
 Basic Java exception handling is managed via keywords: try,
catch, finally, throw, throws.

 try block
 Code that could generate errors put in try blocks
 catch block
 Code for error handling enclosed in a catch clause

 finally block
 The finally clause always executes
 Resources that are opened may need to be closed during
exception handling
 Appears after the last catch block
 It wil not execute if [Link](0) occurs first
How are Java exceptions handled
 throw
 To manually throw an exception, use the keyword throw.

 throws
 throws exception out of the method, requiring it to be caught and
handled by an appropriate exception handler
 Any exception that is thrown out of a method must be specified as such
by a throws clause.
Exception-Handling Struct
try //try block
{
// write code that could generate exceptions
} catch (<exception to be caught>) //catch block
{
//write code for exception handling
}
……
catch (<exception to be caught>) //catch block
{
//code for exception handling
} finally //finally block
{
//any clean-up code, release the acquired resources
}
Examples

Exception handling
Example: Unchecked Exceptions
public class UcException {
public static void main(String args[ ]) {
[Link](args[0]);
}
}
Example: Unchecked Exceptions
compile & execute
Example: Unchecked Exceptions
public class UcException {
public static void main(String args[ ]) {
[Link](args[0]);
}
}
Example: Unchecked Exceptions
Modification
public class UcException {
public static void main(String args[ ]) {
try {
[Link](args[0]);

}catch (IndexOutOfBoundsException ex) {


[Link](“You forget to pass command line argument”);

}
}
Example: Unchecked Exceptions
compile & execute
Example: Checked Exceptions
import [Link].*;

public class CException {


public static void main(String args[ ]) {
FileReader fr = new FileReader (“[Link]”);
BufferedReader br = new BufferedReader(fr);

//read the line


String s = [Link]();
[Link](s);
}
}
Example: Checked Exceptions
compile & execute
Example: Checked Exceptions
Modification
import [Link].*;
public class CException {
public static void main(String args[ ]) {
try {
FileReader fr = new FileReader (“[Link]”);
BufferedReader br = new BufferedReader(fr);
//read the line
String s = [Link]();
[Link](s);
} catch (IOException ex ) {
[Link](ex);
}
}
}
Example: Checked Exceptions
compile & execute
Example: finally block
import [Link].*;
public class FBlockDemo {
public static void main(String args[ ]) {
try {
FileReader fr = new FileReader (“[Link]”);
BufferedReader br = new BufferedReader(fr);

String s = [Link]();
[Link](s);

}catch (IOException ioEx) {


[Link](ioEx);
} finally {
[Link](“finally block always execute”);
//write any clean up code if required
}

}//end of main
}//end of class
Compile & Execute
If “[Link]” isn’t there, it will throw FileNotFoundException
Note that finally block executes

If “[Link]” exist, hopefully no exception would be thrown


Note that finally block still executes
Multiple Catch Blocks
 Possible to have multiple catch clauses for a single
[
try statement
 Essentially checking for different types of exceptions
that may happen

 Evaluated in the order of the code


 Bear in mind the Exception hierarchy when writing
multiple catch clauses!
 If you catch Exception first and then IOException, the
IOException will never be caught!
Example: Multiple catch blocks
/* [Link] contains numbers. After reading number
from file, prints its square on console */

import [Link].*;
public class MCatchDemo {
public static void main(String args[ ]) {
try {
//may throw FileNotFound & IOException
FileReader fr = new FileReader (“[Link]”);
BufferedReader br = new BufferedReader(fr);
//read the line
String s = [Link]();

//may throw NumberFormatException, if s is not no.


int number = [Link](s);
[Link](number * number);
Example: Multiple catch blocks

} catch (NumberFormatException nfEx ) {


[Link](nfEx);
} catch (FileNotFoundException fnfEx) {
[Link](fnfEx);
} catch (IOException ioEx) {
[Link](ioEx);
}
}
}
Compile & Execute
If “[Link]” isn’t there, it will throw FileNotFoundException

If “[Link]” exist and contains a number, Hopefully no exception


would be occurred
The throws clause
The throws clause
 Method doesn’t want to handle exception itself
 It throws the exception, the caller should handle
this exception or throws the exception itself

 A method should specify the exceptions it throws


by placing a throws clause after the parameter list
printStackTrace() is your friend!
 When dealing with exceptions
 Especially when debugging
 printStackTrace() will:
 Show you the full calling history
 With line numbers
 Note:
 Bad idea to eat an exception silently!
 Either printStackTrace() or pass it along to be
handled at a different level
What if

 Method throws back the exception


 No catch blocks matches
 Exception is not handled
calls main
calls method1 calls method2

Java
main
runtime method2 method1
method
system
exception

if not caught
if not caught if not caught
or
or or
throws back
throws back throws back
Example: throws clause
// this example shows the use of throws clasuse and printStackTrace() method

import [Link].*;
public class ThrowsDemo {
//method used to read line from file
public static void method2 () {
try {
FileReader fr = new FileReader(“[Link]”);
BufferedReader br = new BufferedReader(fr);
String s = [Link]();
[Link](s);
}catch (IOException ioEx) {
[Link]();
}
} //end of method
Example: throws clause
// used to call method1
public static void method1 () {
method2();
}

public static void main(String args[]){


ThrowsDemo.method1();
}

}//end of class
Example: throws clause
• Method2 doesn’t want to handle exception itself, so it
throws the exception to the caller
• So method2 modified as
…..
public static void method2 () throws IOException {

FileReader fr = new FileReader();


BufferedReader br = new BufferedReader(fr);
String s = [Link]();
[Link](s);

} //end of method
…….
Example: throws clause
• As method2 is throwing the exception and method1 is invoking method
• So method1 either can handles the coming exception or rethrows it
• If method1 is handling the exception than method1 would be modified as

// used to call method1


public static void method1 () {
try {
method2();
catch (IOException ioEx) {
[Link]();
}
}

public static void main(String args[]){


ThrowsDemo.method1();
}

}//end of class
Compile & Execute
If “[Link]” isn’t there, it will throw FileNotFoundException

If “[Link]” exist there and contains string

You might also like