Exceptions Java 8 Certification

Exceptions Java 8 Certification (OCA Exam) covers only the basics of working with exceptions. Understanding the role of exceptions and type of exceptions are very important for Java Certification. You must read all series article to gain a thorough knowledge on exception hierarchy if you have never worked on a live project. If you already have worked on live project, then you would understand them easily. See the basic exception topics which is the scope of OCA Exam.

Topics to covered under Exceptions

  1. Differentiate among checked exceptions, unchecked exceptions and Errors
  2. Create a try-catch block and determine how exceptions alter normal program flow
  3. Describe the advantages of Exception handling
  4. Create and invoke a method that throws an exception
  5. Recognise common exception classes (such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException)

[ Related Articles : Certification Syllabus, Java Certification 8 Tutorial & Java Certification Practice Papers]

Java Exception

Understanding Exceptions

A program can fail for just about any reason. Here are just a few possibilities:

  1. The code tries to connect to a website, but the Internet connection is down.
  2. You made a coding mistake and tried to access an invalid index in an array.
  3. One method calls another with a value that the method doesn’t support.

As you can see, some of these are coding mistakes. Others are completely beyond your control. Your program can’t help it if the Internet connection goes down. What it can do is deal with the situation. First, we’ll look at the role of exceptions. Then we’ll cover the various types of exceptions, followed by an explanation of how to throw an exception in Java.

The Role of Exceptions

An exception is Java’s way of saying, “I give up. I don’t know what to do right now. You deal with it.” When you write a method, you can either deal with the exception or make it the calling code’s problem. As an example, think of Java as a child who visits the zoo. The happy path is when nothing goes wrong. The child continues to look at the animals until the program nicely ends. Nothing went wrong and there were no exceptions to deal with. This child’s younger sister doesn’t experience the happy path. In all the excitement she
trips and falls. Luckily, it isn’t a bad fall. The little girl gets up and proceeds to look at more animals. She has handled the issue all by herself. Unfortunately, she falls again later in the day and starts crying. This time, she has declared she needs help by crying. The
story ends well. Her daddy rubs her knee and gives her a hug. Then they go back to seeing more animals and enjoy the rest of the day.
These are the two approaches Java uses when dealing with exceptions. A method can handle the exception case itself or make it the caller’s responsibility. You saw both in the trip to the zoo.

You saw an exception in block, “Java Building Blocks,” with a very simple Zoo example. You wrote a class that printed out the name of the zoo:

1: public class Zoo {
2: public static void main(String[] args) {
3: System.out.println(args[0]);
4: System.out.println(args[1]);
5: } }

Then you tried to call it without enough arguments:

$ javac Zoo.java
$ java Zoo Zoo

On line 4, Java realized there’s only one element in the array and index 1 is not allowed. Java threw up its hands in defeat and threw an exception. It didn’t try to handle the exception. It just said, “I can’t deal with it” and the exception was displayed:

ZooException in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 1
at mainmethod.Zoo.main(Zoo.java:7)

Exceptions can and do occur all the time, even in solid program code. In our example, toddlers falling is a fact of life. When you write more advanced programs, you’ll need to deal with failures in accessing files, networks, and outside services. On the OCA exam,
exceptions deal largely with mistakes in programs. For example, a program might try to access an invalid position in an array. The key point to remember is that exceptions alter the program flow.

Return Codes vs. Exceptions

Exceptions are used when “something goes wrong.” However, the word “wrong” is subjective. The following code returns –1 instead of throwing an exception if no match is found:

public int indexOf(String[] names, String name) {
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) { return i; }
}
return -1;
}

This approach is common when writing a method that does a search. For example, imagine being asked to find the name Joe in the array. It is perfectly reasonable that Joe might not appear in the array. When this happens, a special value is returned. An exception should be reserved for exceptional conditions like names being null. In general, try to avoid return codes. Return codes are commonly used in searches, so programmers are expecting them. In other methods, you will take your callers by surprise by returning a special value. An exception forces the program to deal with them or end with the exception if left unhandled, whereas a return code could be accidentally ignored and cause problems later in the program. An exception is like shouting, “Deal with me!”

Understanding Exception Types

As we’ve explained, an exception is an event that alters program fl ow. Java has a Throwable superclass for all objects that represent these events. Not all of them have the word exception in their classname, which can be confusing. Figure 6.1 shows the key subclasses of Throwable.

Java-Exception-Hierarchy

Error means something went so horribly wrong that your program should not attempt to recover from it. For example, the disk drive “disappeared.” These are abnormal conditions that you aren’t likely to encounter.
A runtime exception is defined as the RuntimeException class and its subclasses. Runtime exceptions tend to be unexpected but not necessarily fatal. For example, accessing an invalid array index is unexpected. Runtime exceptions are also known as unchecked exceptions.

A checked exception includes Exception and all subclasses that do not extend RuntimeException. Checked exceptions tend to be more anticipated—for example, trying to read a fi le that doesn’t exist. Checked exceptions? What are we checking? Java has a rule called the handle or declare rule. For checked exceptions, Java requires the code to either handle them or declare them in the method signature.
For example, this method declares that it might throw an exception:

void fall() throws Exception {
throw new Exception();
}

Notice that you’re using two different keywords here. throw tells Java that you want to throw an Exception. throws simply declares that the method might throw an Exception. It also might not. You will see the throws keyword more later in the chapter. Because checked exceptions tend to be anticipated, Java enforces that the programmer do something to show the exception was thought about. Maybe it was handled in the method. Or maybe the method declares that it can’t handle the exception and someone else should.
An example of a runtime exception is a NullPointerException, which happens when you try to call a member on a null reference. This can occur in any method. If you had to declare runtime exceptions everywhere, every single method would have that clutter!

Throwing an Exception

Any Java code can throw an exception; this includes code you write. For the OCP exam, you’ll learn how to create your own exception classes. The OCA exam is limited to exceptions that someone else has created. Most likely, they will be exceptions that are
provided with Java. You might encounter an exception that was made up for the exam. This is fine. The question will make it obvious that these are exceptions by having the classname end with exception. For example, “MyMadeUpException” is clearly an exception.
On the exam, you will see two types of code that result in an exception. The first is code that’s wrong. For example:

String[] animals = new String[0];
System.out.println(animals[0]);

This code throws an ArrayIndexOutOfBoundsException. That means questions about exceptions can be hidden in questions that appear to be about something else.

On the OCA exam, the vast majority of questions have a choice about not compiling and about throwing an exception. Pay special attention to code that calls a method on a null or that references an invalid array or ArrayList index. If you spot this, you know the correct answer is that the code throws an exception.

The second way for code to result in an exception is to explicitly request Java to throw one. Java lets you write statements like these:

throw new Exception();
throw new Exception("Ow! I fell.");
throw new RuntimeException();
throw new RuntimeException("Ow! I fell.");

The throw keyword tells Java you want some other part of the code to deal with the exception. This is the same as the young girl crying for her daddy. Someone else needs to figure out what to do about the exception. When creating an exception, you can usually pass a String parameter with a message or you can pass no parameters and use the defaults. We say usually because this is a convention.
Someone could create an exception class that does not have a constructor that takes a message. The first two examples create a new object of type Exception and throw it. The last two show that the code looks the same regardless of which type of exception you
throw.

These rules are very important. Be sure to closely study everything as displayed below.

Java Exception Type

 

<< Previous Java Certification Chapter : Class Design in Java

>> Next Java Certification Chapter : Try Catch Block in Java

Comments are closed.