Learn about Interfaces and Exception Handling in Java Programming

0
2508
Java

Java

In the previous article, we discussed abstract classes. You saw how you can provide a broad, generic class that may or may not provide a default implementation for your abstract methods. But what if you know that you will never need a default implementation? In other words, you want to force users of your class to provide their own implementation of methods. In this case, you ought to use an interface.

What are Interfaces?

An interface is like a class, except that it has the interface keyword, and it only declares method names. If we go back to our Vehicle analogy, any vehicle should have methods like drive(), stop(), and reverse(). But default implementation should not be added to the base class as these methods are specific to their respective classes. Such methods could be moved to an interface Driveable as follows:

Then a Car class would implement this interface and provide its own implementation:

But what is the difference between an interface and an abstract class?

  1. An interface method cannot contain any code, just the method name
  2. A class that implements an interface is forced to implement all methods contained in this interface. An abstract class, on the other hand, can have some non-abstract methods that needn’t be overridden.
  3. A class can implement from more than one interface at the same time, while it cannot inherit from more than one class concurrently (whether abstract or not).

Exception handling

When an error happens during code execution, it is called an exception. When your application tries to read or write to a file that does not exist, or for which your application does not have the required permission, or when it tries to communicate with nodes on the network using the wrong IP address, an exception is raised. If you didn’t anticipate this exception and write a code to handle it, it will throw an ugly-looking error message, with the stacktrace, to the user. Of course, this is something that you don’t want to happen.

There are two main ways of detecting unusual behavior in your application: error codes and exception objects.

An error code is an old programming concept used in all programming languages. Simply put, a method that executes successfully without any errors would return 0, otherwise it would return a non-zero integer indicating the type of error that occurred. Consider the following example:

Now anyone calling the connect() method should examine the return code, and if it’s not a zero, the application must provide an appropriate workaround.

Because error codes do not provide much detail about what exactly happened, and because it was usually ignored by developers, exception objects were introduced. The exception object is thrown to the virtual machine, which searches for code to handle it. If found, this code gets executed. However, some types of exceptions are not thrown to be handled, for example when the virtual machine runs out of memory there is no handler that can correct or deal with such an error so the whole program must be terminated.

In the following example, we are creating an application that will write some text to a file. Exceptions will be handled appropriately and a useful error message will be presented to the end user when something wrong happens:

Now when I run this code, and because I don’t have write access to the c:\ drive, the following message is shown:

Exception handling starts with a try block, in which the code that may cause an exception is placed. Then the catch block, containing the catch keyword followed by an exception object. In this example we are handling only IO exceptions as they are the ones most likely to happen. However, other non-IO related errors may occur, such as  if you change arr[2] to arr[3] (a nonexistent item in the array), an unhandled ArrayIndexOutOfBoundsException will be thrown. Accordingly, you should anticipate this type of exception as well. Have a look at this modified version of the code:

Now if you run this code, you will receive the following message:

The finally block
You optionally place a finally block after the catch block. Any clean up code should be placed there, for example close any open database connections. A try block must have either a catch or a finally block or both of them, but it cannot be placed without any of them.

Java Programming Course for Beginner From Scratch

Creating custom exceptions

Sometimes you may want to raise your own application-specific exceptions. For example, you may not want the application to write to a file called “test.txt” for some reason, but Java does not have a built in exception class for such a situation. In this case, you have to create your own exception class. An exception class is defined as any normal class, you just have to extend the Exception base class, then call parent methods (like message()) accordingly. Have a look at the following example:

Because you extend the base Exception class, all the class methods (including getMessage()) are available to you. You just need to pass the custom error message that will be used in the exception object. The best way is to supply it to the class in the constructor method. Then, call the base class constructor by using the super keyword and passing the message variable. Now let’s use our newly created exception object.

If you run this code, the following message will be printed to the screen:

Notice, that you have to use the throws keyword after the method name (main()) followed by the exceptions that the code inside this method might use.

Conclusion

In this article, we started by explaining the concept of interfaces, and how they guarantee a class will implement a set of predefined methods. Then, we discussed Java exception handling, how to handle different types of exceptions, and how to create your own custom exception classes.

I hope you find this useful. See you.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here