Exception Handling: What Is An Exception?
Exception Handling: What Is An Exception?
What is an exception?
A notification from the program, prompting the user to fix a big problem .
Exception handing shoudl not be used for the normal flow of control. This
In this case, we have some very well documented global variable that can be
we check error code. Based on thi function and documentation, that means this
went wrong, etc...
o
Whatever values the cError Code has would be spcific to that error.
public class Main {
public static int error_code;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
do_something(s.nextInt());
if (error_code != 0) {
if (error_code == -1) {
System.out.println("Negative number error.");
} else if (error_code == -2) {
System.out.println("Even number error.");
}
error_code = 0;
}
}
s.close();
}
public static void do_something(int a) {
// Clear out error code
error_code = 0;
if (a < 0) {
// a should not be negative. Set error code and return.
error_code = -1;
} else if (a %2 == 0) {
// a should not be even. Set error code and return.
error_code = -2;
} else {
System.out.println("Successfully did something because a was odd!");
}
}
}
The drawback? It's on the progarmmer too check the code every time.
Special Return Value.
Specific return values that are interpreted as errors.
global and special; now, we just examine what is returned instead of looking at
the specific part of the code.
Usually, for functions that are meant to return a reference to some object or
reference type, we can use the value null to indicate something went
wrong.
public class Main {
public static void main(String[] args) {
String haystack = "This is my haystack";
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String needle = s.next();
int position = haystack.indexOf(needle);
if (position == -1) {
System.out.println("Error: could not find needle in haystack");
} else {
System.out.println("Found needle at " + position);
}
}
s.close();
}
}
Notice that indexOf will return the value of the substring, or return -1 if it find
nothing. So we interpret this value. We expect a value of a position to be returned to
use, but alas, not! -1 is a value that is of a specific error. \
Drawbacks?
They're inconsistent.
change.
Exception Handling
Formal mechanism for detecting and dealing with exceptions.
o
Whether and how we use it is upt o us.
No matter wht language--then if there's an exception handling mechanism,
o
Catching. How we handle.
extensibility.
o
We can organize exceptions into families (modularity)
o
We can separate concerns of code that is dealing with normal condition
and code edealing with exceptional cnodition (separation of concerns).
o
Extensible--create new kinds of exceptions, extend different kinds of
exceptions. Write code that handles a group, or an overall type of
exception, even if you don't know where, specifically, it would occur.
Exceptions now wll become objects. Exceptions are objects in and of itself. It
o
The stuff we see here may or may not match the mechanisms provided
in some other language...but it'll be okay
Define checked and uncheked exceptions.
o
Deal with whether or not the situation is something that could occur
and nees to be handled, vs something so exceptional/never expected,
thus when it occurs, it can be handled, but if it occurs, we don't expect it
to occur--something has gone terribly wrong.
o
Java has a way of creating exceptions that should be checked vs
exceptions that don't necessarily need to be checked every time, but if
they ocur, will kill the program. You can check and handle them, but we
don't necessarily want to force hte programmer to handle them if the
programmer is expecting the program to run without ever hitting these
exceptions.
o
Checked Exceptions:
Trying to open a file that doesn't exist.
o
Unchecked Exceptions: Known as Runtime Exceptions!
Logical erros that the programmer doesn't expect to happen.
o
Create a RuntimeException Object, and throw that shit
public Song(String name, String artist,
double length, int rating) {
if (length < 0) {
throw new RuntimeException("Length can not be negative");
}
if (rating < 0 || rating > 5) {
throw new RuntimeException("Rating out of range.");
}
this.name = name;
this.artist = artist;
this.length = length;
this.rating = rating;
}
Throw always expects, on the right side --some kind of exception object.
o
If we are writing code that migh rresult in an exception, and we want to
specify other code to handle other certain exceptional conditions, you put
the code that might cause that exception in the try-block, and you
specify one or more catch-blocks that should handle the
exceptional conditinos as they occur.
o
Each catch-block associated with specific exception type.
o
Declares variable name, and also type name of the exception
we are trying to handle. If it executes perfectly fine, then the tryblock is executed and all the catch blocks get skipped.
If an exception does occur, then the exception was
If something is wrong, notice how the catch thing skips o next line and
tries again.
Extending RuntimeException.
A little more descriptive, or specific exceptions.
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
try {
String name = s.nextLine();
String artist = s.nextLine();
double length = s.nextDouble();
int rating = s.nextInt();
Song a_song = new Song(name, artist, length, rating);
System.out.println("Created song: " + a_song.toString());
s.nextLine();
} catch (RuntimeException e) {
System.out.println("Something went wrong: " + e.getMessage());
s.nextLine();
}
}
s.close();
}
Notice that the catch-block of Song will catch either out of range or negative-length
exceptions.
try {
String name = s.nextLine();
String artist = s.nextLine();
double length = s.nextDouble();
int rating = s.nextInt();
Song a_song = new Song(name, artist, length, rating);
System.out.println("Created song: " + a_song.toString());
s.nextLine();
}
catch (RatingOutOfRangeException e) {
System.out.println("Rating out of range:" + e.getOutOfRangeRating());
s.nextLine();
}
catch (NegativeSongLengthException e) {
System.out.println("Length is negative: " + e.getIllegalLength());
s.nextLine();
}
catch (RuntimeException e) {
System.out.println("Unknown exception: " + e.getMessage());
s.nextLine();
}
}
s.close();
}
Notice that, in this new Main method, only the first error that matches is going
to be run.
Say we entered a song artist, then we write the length as -1 and the rating is 10 We
think that NegativeSongLength will be caught.
And this is what happens. because the length is the first error that is
determined.
But if we have song, artist, 1, 10, then rating is out of range.
Illegal Argument Exception is a RunTime Exception, so it will be caught by the final
catch-block.
When can we suppress an error? How?
You can mark a class as being serializable. This means that a class knows
how to turn itself into a sequence of bites that can be read on a disk.
You can serialize an object on a disk and restore it later.
This has to do with version control and making sure that classses being used
in a project.
If you claim a class is serializable, the objects of your class have to provide a unique
ID.
Sometimes, we need code to run no matter what happens. This is where we can use
finally block.
Anything that has an is-a relationship with Throwable can be used with
the Throw keyword. That's why we can't throw a new ArrayList, or anything like
that.
Throwable's main subclasses are error and exception.
We mostly ignore Error. and Its subclasses are not very important or
o
Now, we can decide what is checked or unchecked exceptions.
What are checked and unchecked exceptions?
Unchecked exceptions include Error, RuntimeException, and their
subclasses. These are the ones which are deemed unchecked. If there's no
difference between the mechanics of checked and unchecked, what does tha
tmean?
All other subclasses of Exception are "checked".
o
It forces the user of the method t explicityl acknowledge--forces strong
software engineering practices by makin it so that the programmer
can't just ignore the issue. They have to deal with it one way or
another.
o
Unchecked exceptions might arise, but still might be able to
handle checked and unchecked exceptions. THERE IS NO
DECLARATION THAT A METHOD MIGHT CAUSE THEM. Unchecked
exceptions are just RuntimeExceptions. The idea behind it is that
unchecked exceptions are ones that don't have to be explicityly
acknowledged or dealt with one way or another. They might occur
and cause your program to crash if you don't have code to catch
occur. It is a part of a larger program that may or may not have methods to
deal with out of range exceptions, negative song lengths. We don't really know
what's supposed to happen when these things end up out of range or negativelenght.
If we don't know what needs to happen, we are better of fspecifying.
Recall that catch blocks are evaluated for having an is-a relationship with the type
of exceptiond eclared in the catch-block. One thing this implies is that you
have to order your catch blocks from SPECIFIC TO GENERAL.
So if we put the RuntimeException block before the OutOfRangeException, then the
RuntimeException block.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
try {
String name = s.nextLine();
String artist = s.nextLine();
double length = s.nextDouble();
int rating = s.nextInt();
Song a_song = new Song(name, artist, length, rating);
code to say, for every single ofe of those checked exceptions, it will still find it
somehow.
What aboue the addition of catch (Exception e) {}?
You do have to put in a catch block that will run, which has an is-a relationwith each
checked exception.
GENERAL PRINCIPLE: BE SPECIFIC.
Princilpes for using exceptions--one, if we have an exception that describes a
o
If we want it to be unchecked, subclass RuntimeException.
o
If we want it to be checked, subclass Exception.
HOW PROMINENT DO WE WANT THE EXCEPTION TO BE IN OUR
PROGRAM'S TExT?
o
Do you expect other programmers to use the program that you write?
Do they expect that you will account for these errors to be caught? Then
you need to be catching exceptions.
o
Over the years, however, programmers hate the catch/specify
rule...It encourages people to make this code try to block all the
catches from exception...so most people use unchecked
exception.
o
We can try to avoid using checked exceptions, omost of the time. It
works against good practice, etc.
Scanner can sraise exceptions when it is asked to parse something that it does not
know.
So the specific exception scanner raises-- NoSuchElementException. This might
be something that our program can recover from.
But if we don't have a try block and don't catch the NoSuchElementException...
Scanner stays open even though we try to close it.
Anyone that uses this method needs to acknowledge that hey, if this file is not the
right format, you need to either deal with it or indicate that this has to be fixed.
In the actual method, we catch the exception that is raised by the scanner
and, what we do with it, is create a new exception and throw that one
instead!
try {
Playlist p = Playlist.readFromFile(playlist_file);
p.print();
} catch (PlaylistFormatException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
And in our program, in order to use readFromFile, we find a way to catch this
FormatException.
Say we asked for a double, but find ther eis no double here.
Then the code reading ht eplaylist would turn this into a more specific
exception.
Our program had to acknowledge that these exceptions that oculd occur...but if it
didn't, then the program will say, UNHANDLED EXCEPTION TYPE.
If you really want this unchecked exception to go all the way to main, the
main method can also specify these things.
public static void main(String[] args) throws PlaylistFormatException {
if (args.length != 1) {
If you canc atch low-level exceptions and turn them into higher-level
Say that we open scanner = new Scanner(new File (filename((; before the try-block.
Well, the program will complain. Just catching filenotFound and closing the program
is not always the right thing to do. We should change this so that instead of
catching it...
Since we don't know what the program is going to do, we should do specify.
We can add it to the list of exceptions that our program can throw.
A different program has a small loop that asks for the playlist to be read. If the file is
not found, it gives us a message and tells us to try again. If we can't find the file,
then there's nothing to do; the program just fails.
But a different program will have a different response ot a file being unfound.
We want to catch as late as we can. We want that exception to bubble up to give
us a high enough view for the system or the program as a whole.
null and certain values to not be in range, if we know the method will
complain if the thing given to it was null or out of range, just....let it happen.
o
But intstead of letting the illegal situation or problem keep going into a
deeper level.
The code we need to write to catch an exception early may be just as hard as
At the same time, by throwing early, we cathct he problem earlier. So this is good
for nullPointerReferences.
FOR SUBPICTURE::
We have SubPicture class that takes in a Picture reference and represents the
subArea of it. We encapsulate a reference from that source picture and get
some information as that subarea.
To construct SUbPicture, we don' teven have to test that the Picture object is
null. Null is a valid value for reference types. We can save that as our source
picture in the geometry.
But...later on, when we call getPixel, when we try to use that reference to the
Later on, in some other pat of the code that's very far away, then we
type and then e. The next block can resuse e and reuse the same variable
name in the declaration.
A catch-block associated with an exception class cannot precede a catch
blocks.
This catch-or-specify requirement not only affects how we declare the methd--but it
also affects how we declare interfaces.