JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Top 11 Java Exception Best Practices

February 13, 2016 by Krishna Srinivasan Leave a Comment

In my previous tutorial about Java exceptions, I have covered suppressed exceptions and java exception handling. It is one of the important coding practice to do efficient and foolproof exception handling for your projects. To achieve that, you must have a good knowledge on best practices used for exception. This tutorial will highlight the most significant best practices used by the Java programmers to improve the quality of exception handling. If you have any questions, please write it in the comments section.

Java Exceptions Best Practices

1. Do not suppress / swallow the exception in catch block

[code lang=”java”]
public class ExceptionExample {
public FileInputStream testMethod1(){
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}catch (IOException e){
return null;
}
return fileInputStream;
}
public static void main(String[] args){
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

Swallowing the exception is one of the bad practice in the exception handling. In the above example, whatever exception thrown will be ignored completely and there is no clue on where is the problem. It is always best practice to throw the exception back to outer layer or handle the exception and perform some alternative solution.

[code lang=”java”]
public class ExceptionExample {
public FileInputStream testMethod1() throws IOException{
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}catch (IOException e){
throw e;
}
return fileInputStream;
}
public static void main(String[] args) throws IOException{
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

2. Declare specific exception in throws clause of method block

Writing like the below throws clause defeat the whole purpose of the checked exceptions:

[code lang=”java”]
public FileInputStream testMethod1() throws Exception{
[/code]

This is not good practice. We must always try to use the most specific exception class that are thrown from the program. The most appropriate throws clause would be:

[code lang=”java”]
public FileInputStream testMethod1() throws IOException{
[/code]

3. Catch specific exception classes

It is always good idea to catch the specific classes that are thrown from the application. If there are multiple exceptions thrown from the application that are falls under the same type, catching only the super class is not an good idea.

For instance, if your code is throwing both FileNotFoundException and IOException, have two catch clauses for both the exceptions on hierarchy instead of writing one catch clause with IOException or in worst cases just writing catch clause for Exception.

Here is the correct way to catch the specific exception class:

[code lang=”java”]
try {
//some statements
catch(FileNotFoundException e){
//handle here
}
catch(IOException e){
//handle here
}
[/code]

You should never catch the exception like this:

[code lang=”java”]
try {
//some statements
catch(Exception e){
//handle here
}
[/code]

4. Release the resources in Finally block

When you are opening a database connection, file operations or any other resources centric operations would be closed properly, otherwise that will lead to a performance issue for your application. For instance, when you have opened a database connection and performing CRUD operations, any exceptions thrown will leave the connection open for ever and it will never be closed.

To avoid the worst scenario, it is always good practice to close the opened resources in the finally block. Here is example code for closing the database connections in the finally block:

[code lang=”java”]
finally {
try {
if (con != null) {
con.close();
}
if (stat != null) {
stat.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
[/code]

Next time when you see your team member not using the finally block for closing the resources, pinch him to follow the best practice :).

5. Exceptions Impacts Performance

Java Exceptions Performance

Exceptions are very very expensive. This statement should be remembered by every Java programmer while they are writing the code. Creating an exception is very slow operation and throwing an exception cost you around 1-5 microseconds. When the exceptions are propagated to multiple levels, then it will slow down the entire application.

  • Use the exceptions in the exceptional conditions
  • Use the exceptions when it is recoverable

While exception usage is good you should better avoid capturing too many stack traces in your program. In many cases they are not even necessary to understand the problem – especially if they cover a problem you already expect. The exception message therefore might prove as being enough information.

6. Use Standard Exceptions

Don’t write your custom exceptions if the problem can be dealt with the in-built exceptions. Java API itself provides hundreds of  exceptions for various conditions. First try to use the same exceptions for your application, if that is not sufficient and not providing meaning of your business scenario, then create your own custom exceptions.

If you use the in-built exceptions, then any new developer or outside world also will be able to understand the code. You need not lock your code with your own API.

7. Wrap the exceptions correctly

When you re-throw your applications, it is important to wrap the original exceptions properly, otherwise the origin of the exceptions will be lost. Look at the example:

[code lang=”java”]
import java.io.IOException;
public class HelloWorld{
public static void main(String []args) throws Exception{
try{
throw new IOException("IOException");
}catch (IOException e){
throw new ExampleException1("Example Exception and " + e.getMessage());
}

}
}
class ExampleException1 extends Exception{
public ExampleException1(String s, Throwable t){
super(s,t);
}
public ExampleException1(String s){
super(s);
}
}
[/code]

Output for the above program will be as below:

[code]
Exception in thread "main" ExampleException1: Example Exception and IOException
at HelloWorld.main(HelloWorld.java:8)
[/code]

In the above output, the IOException stack trace is lost because we have not used the correct constructor to wrap the exceptions. Modify the catch block as below, this the proper way of wrapping the exceptions:

[code lang=”java”]
catch (IOException e){
throw new ExampleException1("Example Exception",e);
}
[/code]

The output will be:

[code]
Exception in thread "main" ExampleException1: Example Exception
at HelloWorld.main(HelloWorld.java:8)
Caused by: java.io.IOException: IOException
at HelloWorld.main(HelloWorld.java:6)
[/code]

8. Avoid throwing exception from finally block

[code lang=”java”]
try {
method(); //here throws first exception
} finally {
shutdown(); //If finally blockthrew any exception the first exception will be lost forever
}
[/code]

In the above example snippet, note that there is a possibility of finally block also would thrown an exception. If it throws an exception, then first exception will be lost in case both the exception thrown at the same time. It is good practice to handle the exception in finally block or log the error messages. But, never thrown any exception from the finally block.

9. Don’t use exceptions for flow control

You should never use exception for controlling the flow of your program. For example, instead of using the if condition, using exception to validate a scenario is one of the worst practice that impacts the performance if your application.

10. Don’t catch Throwable class

You should never catch Throwable class in your program. Error also subclass of Throwable class, the errors are not even recoverable by the JVM itself.

11. Document the exceptions

Make it a habit to document all the exceptions in your application. When you write a custom exception in your application, no one else in the world other than you know the cause for that exception :). So, you must do a favor to your team by writing a good explanation about the cause of that exception and how to handle it. Trust me, that will be a great help when needed.

 

Filed Under: Java Tagged With: Java Exceptions

java.net.ConnectException Example

February 12, 2016 by Krishna Srinivasan Leave a Comment

java.net.ConnectException is thrown when client socket is not able to connect to the server socket. java.net.ConnectException is subclass of java.net.SocketException. In this short tutorial, I am going to write a simple program for client socket that sends message to the server socket. Then server socket process the message and prints it. When there is a issue in client for connecting to the server socket, java.net.ConnectException will be thrown. Please read our previous article on WebSocket Support in Java EE 7.

Following are the most common scenarios when this exception is thrown:

  • When server is not started and client is trying to connect to the server
  • When client is trying to connect to the wrong port number
  • When client is trying to connect to the wrong host name or IP address
  • When server and client is located remotely. But, they are in the different network where connection is not allowed.

java.net.ConnectException Example

Here is the simple example that demonstrates the ConnectException.

[code lang=”java”]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ConnectExceptionExample {
public static void main(String[] args) {
new Thread(new ExampleServer()).start();
new Thread(new ExampleClient()).start();
}
}

class ExampleServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
while (true) {
try {
serverSocket = new ServerSocket(1111);
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Message Received :" + inputReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

class ExampleClient implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
Thread.sleep(1000);
socket = new Socket("localhost", 1111);
PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
outWriter.println("Message from Client!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
[/code]

When you run the above program, you will get the following output:

[code]
Message Received :Message from Client!
[/code]

Now, change the port number to something like this for server and then run the application.

[code lang=”java”]
serverSocket = new ServerSocket(1112);
[/code]

You will get the java.net.ConnectException as below:

[code]
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at infy.org.ExampleClient.run(ConnectExceptionExample.java:47)
at java.lang.Thread.run(Thread.java:722)
Exception in thread "Thread-1" java.lang.NullPointerException
at infy.org.ExampleClient.run(ConnectExceptionExample.java:59)
at java.lang.Thread.run(Thread.java:722)
[/code]

I hope this example will help you to understand when java.net.ConnectException is thrown from your application. If you have any questions, please write it in the comments section.

Filed Under: Java Tagged With: Java Exceptions

EOFException Example in Java

February 6, 2016 by Krishna Srinivasan Leave a Comment

EOFException in Java is thrown when end of file is reached unexpectedly while processing the input. These exceptions are thrown while working the DataInputStream, ObjectInputStream and RandomAccessFile classes. All these classes are using one of the stream classes like FileInputStream for reading the data. When there is no data available in the stream by DataInputStream is trying to read some data, then this exception will be thrown. This is a subclass of IOException.

EOFException Example

This exception is thrown when you reach the end of a stream (end of file, or peer closes the connection):

  • read() method returns -1
  • readLine() method returns null
  • readXXX() for any other X throws EOFException. Here X means the method name would be readInt, readFloat, etc. Say, when you are trying to read any of these methods, it would expect some specified length of streams in the underlying FileInputStream, if that is empty then EOFException will be thrown. Also when you are using readInt and only float is available in the file will throw the same exception.

Here is the example for an application which throws EOFException:

[code lang=”java”]
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExceptionExample {
public void testMethod1(){
File file = new File("test.txt");
DataInputStream dataInputStream = null;
try{
dataInputStream = new DataInputStream(new FileInputStream(file));
while(true){
dataInputStream.readInt();
}
}catch (EOFException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
finally{
try{
if (dataInputStream != null){
dataInputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

When you run the above program, you will get the following exception:

[code]
java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:16)
at logging.simple.ExceptionExample.main(ExceptionExample.java:36)
[/code]

I have enforced the above program to throw the EOFException by making the while loop condition with true. This will make your program run even after reading all the data and throw the exception. Application programmer has to ensure that the data read from the stream is correct and closed when there is no more data in the stream

I hope this tutorial provided good idea on the scenarios when EOFException is thrown from a Java application. If you have any questions, please write it in the comments section.

Filed Under: Java Tagged With: Java Exceptions

IOException Example in Java

February 6, 2016 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain one of the most common Java exception that is well known by all the Java developers. IOExceptions are thrown when there is any input / output file operation issues while application performing certain tasks accessing the files. IOException is a checked exception and application developer has to handle in correct way.

IOException has many sub classes that are specific in nature. That means, when your application searching to read a file, if the file is not found that there is a ileNotFoundException to be thrown. FileNotFoundException is a subclass of IOException. Like this there are many subclasses defined in exception packages for handling the specific scenarios.

Java IOException
                                          This figure shows key facts about IOException in Java application

Few of the well known classes are:

  • FileNotFoundException
  • EOFException
  • SSLException
  • UnSupportedEncodingException
  • SocketException

IOException Example

Here is simple example for IOException:

[code lang=”java”]
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExceptionExample {
public FileInputStream testMethod1(){
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}catch (IOException e){
e.printStackTrace();
}
finally{
try{
if (fileInputStream != null){
fileInputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return fileInputStream;
}
public static void main(String[] args){
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

When you run the above program where there is no file present in the file system, you would get the following exception:

[code]
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:12)
at logging.simple.ExceptionExample.main(ExceptionExample.java:30)
[/code]

This is one of the IOException, but depends on the different problems in reading the file, your application may throw some other IOExceptions.

If you look at the above code:

  • The above code tries to read the file test.txt from the file system.
  • It throws the FileNotFoundException, that is a subclass of IOException
  • IOException and all the subclasses are checked exceptions
  • If you create a file names test.txt in the correct path and run the above program, you will not get any exception.

Filed Under: Java Tagged With: Java Exceptions

Java InvalidPropertiesFormatException Example

November 8, 2014 by Krishna Srinivasan Leave a Comment

When we are using the collection of properties, if the input does not conform to the valid XML document type with the appropriate properties specification at that time an exception is thrown called InvalidPropertiesFormatException, to indicate operation could not be completed. This example explains about that exception.

Java InvalidPropertiesFormatException Class Declaration

[code lang=”xml”]
public class InvalidPropertiesFormatException extends IOException
[/code]

In the above declaration, the class InvalidPropertiesFormatException is the sub class of the IOException which handles the InvalidPropertiesFormatException.

Java InvalidPropertiesFormatException Constructors

Constructor Description
InvalidPropertiesFormatException (String message) It creates a constructor called InvalidPropertiesFormatException for the specified parameter message of type string. The parameter message is saved which is invoked later by using the method Throwable.getmessage ().
InvalidPropertiesFormatException (String cause) It creates a constructor called InvalidPropertiesFormatException for the specified parameter cause of type string. The parameter cause is saved which is invoked later by using the method Throwable.getcause ().

Java InvalidPropertiesFormatException Example

Below Example illustrates InvalidPropertiesFormatException which is thrown when you try to load a set of properties from an XML file. In the below example we are using the DTD file definitions and an XML that must be complaint with the DTD file. If there is any deviation, there should be an exception.

Properties.dtd Example

Below is the DTD for XML file to be loaded and saved it with the name properties.dtd.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT properties (comment?, entry*) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>
[/code]

sampleproperties.xml Example

Following is a XML file saved with the name sampleproperties.xml. The XML file must contain the same element as defined in the DTD.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Information</comment>
<entry key=”name”>Tanmay Patil</entry>
<entry key="company">Tutorials Point</entry>
<entry key="phone"> (0111) 123-456</ entry >
</properties>
[/code]

NOTE:<!DOCTYPE properties SYSTEM “http://java.sun.com/dtd/properties.dtd”> line has to be included in the prolog section of your XML file, as it is not allowed to use a DTD other than this while calling the java.util.Properties.loadFromXML ().

Following is a example shows how to load a set of properties from an XML file.

[code lang=”xml”]
package javabeat.net.corejava;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class Example_InvalidFormat {
public static void main (String args []) {
Properties p1 = new Properties ();
String property_file = "properties.dtd";

try {
System.out.println ("Before properties load: " + p1);
prop.loadFromXML (new FileInputStream (property_file));
System.out.println ("After properties load : " + p1);

} catch (InvalidPropertiesFormatException e) {
e.printStackTrace ();
} catch (FileNotFoundException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
[/code]

  • String property_file = “properties.dtd”; line specifies the XML file name which you want to load.
  • prop.loadFromXML (new FileInputStream (property_file)); lines reads the specified XML file name. When it encounters, the file name and finds that name specified is not the XML file instead is a DTD file. Then, main throws an InvalidPropertiesFormatException exception.

If you run the above example, you would get the exception thrown like in the below screenshot.

Java-InvalidpropertyFormatException-Example

Filed Under: Java Tagged With: Java Exceptions

javax.naming.NameNotFoundException: Name is not bound in this Context Exception

May 3, 2014 by Krishna Srinivasan Leave a Comment

When you are working with the JNDI look up, quite often you would encounter the javax.naming.NameNotFoundException thrown by your application. JNDI names are registered in the registery, if you try to access the name which is not registered or by the wrong format, you would get the javax.naming.NameNotFoundException. Lets look at the below code for accessing the JNDI names using InitialContext.

[code lang=”java”]
Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
String mydata = (String)envEntryContext.lookup("varName");
[/code]

When you run the above code, if the name “varName” not found under the context “java:comp/env”, then you will get the below exception. You have correct the name for fixing this issue.

[code]
javax.naming.NameNotFoundException: Name [varName] is not bound in this Context. Unable to find [varName].
at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
at javabeat.net.util.HelloServlet.doGet(HelloServlet.java:20)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[/code]

Filed Under: Java EE Tagged With: Java Exceptions, JNDI

java.sql.SQLException: Can’t call commit when autocommit=true Exception

May 3, 2014 by Krishna Srinivasan Leave a Comment

When you work with JDBC application, by default the auto commit is set to true, after the transaction is completed all the transactions are committed to the database. When it is set as true, you can not explicitly call the commit method. If you call the connection.commit() method, then the below exception will be thrown.

[code]
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: Can’t call commit when autocommit=true
at javabeat.net.spring.core.Country.insertCountryName(Country.java:54)
at javabeat.net.spring.core.SpringStandAloneExample.main(SpringStandAloneExample.java:11)
Caused by: java.sql.SQLException: Can’t call commit when autocommit=true
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:914)
at com.mysql.jdbc.Connection.commit(Connection.java:2275)
at javabeat.net.spring.core.Country.insertCountryName(Country.java:51)
[/code]

Filed Under: Java Tagged With: Java Exceptions, JDBC

How To Resolve java.lang.IllegalAccessException

April 24, 2014 by Krishna Srinivasan Leave a Comment

This example shows when the java.lang.IllegalAccessException is thrown in your application. When an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, if that method is not accessible to your application (probably the modifier is private or not accessible one), then your application will throw java.lang.IllegalAccessException. This exception is extended from java.lang.ReflectiveOperationException.

Lets look at this simple example which throws java.lang. IllegalAccessException.

ClassNewInstanceExample.java

[code lang=”java”]
package javabeat.net.lang;

/**
* java.lang.IllegalAccessException Example
*
* @author Krishna
*
*/
public class ClassNewInstanceExample {
public static void main(String[] args) throws IllegalAccessException,
InstantiationException {
Class<?> classVar = ExampleClass.class;
ExampleClass t = (ExampleClass) classVar.newInstance();
t.testMethod();
}

}
[/code]

ExampleClass.java

[code lang=”java”]
package javabeat.net.lang;

public class ExampleClass {
private ExampleClass(){

}
public void testMethod(){
System.out.println("Method ‘testMethod’ Called");
}
}
[/code]

Exception Trace…

If you run the above program, you will get the following exception trace as the output.

[code]
Exception in thread "main" java.lang.IllegalAccessException: Class javabeat.net.lang.ClassNewInstanceExample can not access a member of class infosys.net.lang.ExampleClass with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javabeat.net.lang.ClassNewInstanceExample.main(ClassNewInstanceExample.java:13)
[/code]

The solution for this problem is to check the method or constructor whether it has the proper access modifier to access in your application.

Filed Under: Java Tagged With: Java Exceptions, Java Lang

FileNotFoundException in Java

March 20, 2014 by Krishna Srinivasan Leave a Comment

If you are working with the File APIs in Java, it is common that you would encounter the FileNotFoundException. This is a subclass of IOException. This Java exception is thrown by the classes FileInputStream, FileOutputStream, and RandomAccessFile. These classes trying to access a file in the system for the purposes of reading or writing into that file. Java doesn’t have the facility to check if the file is present at the compile time. When you execute the program, you would get the FileNotFoundException if that file is not exist.

It is a checked exception that must be handled by the application. Take the appropriate steps to print the valid messages to the user if this exception is thrown. Look at the below example:

[code lang=”java”]
package javabeat.net.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* File Not Found Exception example
* @author Krishna
*
*/
public class JavaFileExample {
public static void main(String[] args) {
File file = new File("D:/JavaTest.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
while (fileInputStream.read()!=-1){
System.out.println(fileInputStream.read());
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
try{
fileInputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
[/code]

The above program would throw an exception if the file “JavaText.txt” is not in the mentioned path. You will get the following exception.

[code]
java.io.FileNotFoundException: D:\JavaTest.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at javabeat.net.util.JavaFileExample.main(JavaFileExample.java:17)
Exception in thread "main" java.lang.NullPointerException
at javabeat.net.util.JavaFileExample.main(JavaFileExample.java:27)
[/code]

Filed Under: Java Tagged With: Java Exceptions, Java File IO

NullPointerException in Java

March 17, 2014 by Krishna Srinivasan Leave a Comment

One of the most common and nightmare for the Java programmers are getting the NullPointerException while running the Java application. This exception is defined at the “java.lang” package and the purpose of the exception is to detect if an object is used without any content. Here you must understand the difference between Reference and Object. A reference variable is just a handler which hold an actual object in a memory. In the below example:

[code lang=”java”]
Employee emp = new Manager();
[/code]

In the above code, “emp” is reference of Employee class which holds the object of type “Manager”. Here you can assume that if the “emp” reference is not assigned to any of the object, then it will have empty reference or null value. Look at the below example:

[code lang=”java”]
package javabeat.net.core;

public class NullPointerExceptionExample {
public static void main(String args[]){
Employee emp = null;
emp.method();
}
}
abstract class Employee{
public abstract void method();
}
class Manager extends Employee{
public void method(){
System.out.println("test method");
}
}
[/code]

If you run the above program, you will get the following exception:

[code]
Exception in thread "main" java.lang.NullPointerException
at javabeat.net.core.NullPointerExceptionExample.main(NullPointerExceptionExample.java:6)
[/code]

The above example is very much straight forward implementation to show the reason for the NullPointerException. However, in the real scenario it will be more complicated to detect the object reference if its null. The only way to avoid the situation is to do the good practice of checking null values before accessing any values. Look at the same example below:

[code lang=”java”]
package javabeat.net.core;

public class NullPointerExceptionExample {
public static void main(String args[]) {
Employee emp = null;
if (emp != null) {
emp.method();
} else {
emp = new Manager();
emp.method();
}
}
}

abstract class Employee {
public abstract void method();
}

class Manager extends Employee {
public void method() {
System.out.println("test method");
}
}
[/code]

I have added the “if” condition to check if the “emp” reference is pointing to the null, if so I am creating the object and then calling it. Like this you can take the manual handling to avoid the NullPointerException in your application.

Filed Under: Java Tagged With: Java Exceptions, Java Lang

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved