Now we have talked a lot about exceptions in Java. We have
seen how to handle exceptions using the try-catch block and throwing
exceptions. We have also seen how to throw multiple exceptions and the order in
which exceptions should be thrown if they have a parent child relationship
because of polymorphism.
There is one last thing that I have to teach you about
exceptions. There are two types of exceptions in Java. These are the checked
exceptions and unchecked exceptions.
So far, we have been dealing with checked exceptions, which
force us to handle them before the program can compile. However, there is the
second group of exceptions that we haven’t yet dealt with, known as the
unchecked exceptions.
With unchecked exceptions, the program will compile, but will
then exit with an error. Unchecked exceptions are also called runtime
exceptions because they only manifest when the program is compiled.
However, please note that when your program has runtime
exceptions, it is indicative of very serious and fundamental problems in the
code. In the following example, we are going to look at three common examples
of runtime errors. Note that in principle, these errors should not exist.
Divide by
Zero Runtime Errors
If you try to divide any number by zero, Java will not
complain, but when you run the program, it will not compile. Instead, it will
throw an ArithmeticException. You will either have to fix the error in the
code, or handle the exception by throwing it or using a try-catch block.
int y = 0;
int x = 5;
int
z = x/yFigure 1: Divide by zero ArithmeticException
Trying to
Access an Array Index beyond its Bounds
If you try to access an array index beyond the highest index,
Java will at runtime throw an ArrayOutOfBoundsException. Remember that array
indices always start from zero. So if the array has 3 items, this means that
the third item has the index 2. So if you try to access index 3, which doesn’t
exist, you will get a runtime error.
String[] names = {“Brian”, “Veronicah”, “Anthony”};
System.out.println(names[3]);Figure 2: ArrayIndexOutOfBoundsException
Null
Pointer
You may create a string reference but point it to nothing,
like this: String name = null;
If you
try to use a method on an uninitialized object i.e. on the reference variable,
Java will throw a NullPointerException at runtime.Figure 3: NullPointerException
While you can handle runtime exceptions when you know they
exist, the ideal scenario is to never have them in the first place. Some
runtime exceptions such as the NullPointerException are usually common among
people learning Java for the first time, because they might not have learnt how
to initialize objects.
In the next tutorial, we are going to look at abstract
classes in Java.
In case you have any question on Exceptions or any other part
of this course, please let me know by dropping them in the comments section
below.
No comments:
Post a Comment