Exceptions Java 8 Certification

Exceptions Java 8 Certification(OCA Exam) covers only thebasics 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, uncheckedexceptions and Errors
  2. Create a try-catch block and determine how exceptions alternormal 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 asNullPointerException, 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 doesnt support.

As you can see, some of these are coding mistakes. Others are completely beyond yourcontrol. Your program cant help it if the Internet connection goes down. What it can do isdeal with the situation.First, well look at the role of exceptions. Then well 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 Javas way of saying, I give up. I dont know what to do right now. Youdeal with it. When you write a method, you can either deal with the exception or make itthe calling codes problem.As an example, think of Java as a child who visits the zoo. The happy path is whennothing goes wrong. The child continues to look at the animals until the program nicelyends. Nothing went wrong and there were no exceptions to deal with.This childs younger sister doesnt experience the happy path. In all the excitement she trips and falls. Luckily, it isnt 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 laterin 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 seeingmore animals and enjoy the rest of the day. These are the two approaches Java uses when dealing with exceptions. A method canhandle the exception case itself or make it the callers responsibility. You saw both in thetrip to the zoo.

You saw an exception in block, Java Building Blocks, with a very simple Zooexample. 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 theres only one element in the array and index 1 is not allowed.Java threw up its hands in defeat and threw an exception. It didnt try to handle the exception.It just said, I cant 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, youll need todeal 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 toaccess an invalid position in an array. The key point to remember is that exceptions alterthe program flow.

Return Codes vs. Exceptions

Exceptions are used when something goes wrong. However, the word wrong issubjective. The following code returns 1 instead of throwing an exception if no match isfound:

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 thatJoe might not appear in the array. When this happens, a special value is returned. Anexception should be reserved for exceptional conditions like names being null.In general, try to avoid return codes. Return codes are commonly used in searches, soprogrammers are expecting them. In other methods, you will take your callers by surpriseby returning a special value. An exception forces the program to deal with them or endwith the exception if left unhandled, whereas a return code could be accidentally ignoredand cause problems later in the program. An exception is like shouting, Deal with me!

Understanding Exception Types

As weve explained, an exception is an event that alters program fl ow. Java has a Throwablesuperclass for all objects that represent these events. Not all of them have the word exceptionin their classname, which can be confusing. Figure 6.1 shows the key subclasses ofThrowable.

Java-Exception-Hierarchy

Error means something went so horribly wrong that your program should not attempt torecover from it. For example, the disk drive disappeared. These are abnormal conditionsthat you arent likely to encounter. A runtime exception is defined as the RuntimeException class and its subclasses. Runtimeexceptions tend to be unexpected but not necessarily fatal. For example, accessing an invalidarray index is unexpected. Runtime exceptions are also known as unchecked exceptions.

A checked exception includes Exception and all subclasses that do not extendRuntimeException. Checked exceptions tend to be more anticipatedfor example, tryingto read a fi le that doesnt exist.Checked exceptions? What are we checking? Java has a rule called the handle or declarerule. For checked exceptions, Java requires the code to either handle them or declare themin the method signature. For example, this method declares that it might throw an exception:

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

Notice that youre using two different keywords here. throw tells Java that you want tothrow an Exception. throws simply declares that the method might throw an Exception. Italso 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 dosomething to show the exception was thought about. Maybe it was handled in the method.Or maybe the method declares that it cant handle the exception and someone else should. An example of a runtime exception is a NullPointerException, which happens whenyou try to call a member on a null reference. This can occur in any method. If you had todeclare 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, youll learn how to create your own exception classes. The OCA exam is limited toexceptions 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 theclassname end with exception. For example, MyMadeUpException is clearly anexception. On the exam, you will see two types of code that result in an exception. The first is codethats wrong. For example:

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

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

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

The second way for code to result in an exception is to explicitly request Java to throwone. 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 theexception. This is the same as the young girl crying for her daddy. Someone else needs tofigure out what to do about the exception.When creating an exception, you can usually pass a String parameter with a message oryou 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 takesa 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

All OCJP Java Certification Tutorials

  1. Oracle (OCJP) Java Certification Exam
  2. Java Building Blocks Java 8 Certification
  3. Operators And Statements
  4. Java Core API
  5. Java Class Design
  6. Java Exception
  7. Java Try-Catch Block
  8. Exceptional Handling in Java
  9. Common Exception in Java