Add to Google Reader or Homepage

class or interface required

class or interface required:

This error usually arises when the keyword class is  missed while writing the name of the class.so we should ensure that the class keyword is included.

Example:

public vehicle
{
int vno;
String vcolor;

int getvno();
String getvcolor();
}

This code will show an error like class or interface is required, as the keyword class is not included.

Exception in thread "main" java.lang.ClassNotFoundException

ClassNotFoundException

 

The ClassNotFoundException is thrown when an application tries to load in a class through its string name using:

The forName() method in class Class
The findSystemClass() method in class ClassLoader .
The loadClass() method in class ClassLoader.
 
but no definition for the class with the specified name could be found,ie if a class with the given name is not available during loading then this exception would be thrown.

Example:

 

import java.util.*;
import java.io.*;
 import java.lang.reflect.*;
 public class Ex
 {
 public static void main(String args[])
 {
 String name;
 System.out.println("Enter the class to be loaded");
 Scanner in=new Scanner(new InputStreamReader(System.in));
 name=in.next();
try
{
Class cl=Class.forName(name);
System.out.println();
Constructor[] constructors = cl.getDeclaredConstructors();
for (Constructor c : constructors)
System.out.println(c.getName());
Method[] methods = cl.getDeclaredMethods();
for (Method m : methods)
System.out.println( m.getName());
}

catch(ClassNotFoundException e)
{
e.printStackTrace();
}

}
}



The above program will ask the user to enter a class name to display its constructors and methods.If a class with the given name is not available then the ClassNotFoundException will be thrown.

Exception in thread "main" UnknownHostException

UnknownHostException:

The UnknownHostException occurs when the java program uses the socket to create a connection to the remote host.There are two main reasons for this exception to occur.

1.This exception is usually thrown when DNS(Domain Name Server) is unable to translate the host name into a valid IP address.This could be a problem due to DNS server or the host name that you specified may be invalid.

2.The second reason is that "connection may be unavailable" for some reason.

Example:

 public class SocketTest
 {
    public static void main(String[] args)
    {
       try
       {
          Socket s = new Socket("net01.example.blospot.in", 2034);
          try
          {
             InputStream istream = s.getInputStream();
             Scanner in = new Scanner(istream);

             while (in.hasNextLine())
             {
                String line = in.nextLine();
                System.out.println(line);
            }
          }
          finally
          {
             s.close();
          }
       }
       catch (IOException e)
       {
          e.printStackTrace();
       }
    }
 }
 
 
In this above code the UnknownHostexception would occur when the socket tries to connect to
the remote host since the host name that i have been trying to connect is not available.
 
So if you come across this error ensure that whether you have given the valid  address or not.
If you indeed entered the valid address then check whether the connection is available. 

 

Exception in thread "main" java.lang.NoClassDefFoundError

NoClassDefFoundError: 


Reasons

  1. This error would occur if you execute the program with a modified classname. consider for eg. Let the name of the program be Example.java and if u compile and execute the program as follows
  • javac Example.java
  • java example

    2. Whenever a java program is compiled it creates a class file.This class file is used to launch the program.We all know about the variable classpath.The classpath lists all directories and archive files which are all starting points for locating classes.


So when a program is to be executed jvm will look for the class file(of the program) in the path specified in the variable CLASSPATH.

If the class is not available in the path specified by the CLASSPATH variable then this error would appear.

  Correction

 

1.This error can be resolved by eliminating the accidental mistyping of the classname during launching.

2.If the CLASSPATH variable is modified to include the class file then this error can be avoided.

Note:

  •  The CLASSPATH can be set to multiple values each separated by semi colon as follows                           
java -classpath c:\classdir;.;c:\archives\archive.jar Example.

  • The CLASSPATH can also be made to point to the current location by using the dot(.) as follows.   
  java -classpath .; Example

  • If a class file belongs to a jar then the jar must be added to the CLASSPATH variable.


Exception in thread "main" java.io.eofexception

EOFException:

In this post i am going to discuss about the End of File(EOF) exception.EOFexception extends IOException and is thrown while performing I/O operations.

This exception is usually thrown when the end of file (EOF) is reached unexpectedly while reading the input file.Note that,this exception will also be thrown if the input file contains no data in it.

I have explained this EOF exception with the following program.The following program tries to read the file "exam.txt" and prints its contents.When the reader has reached the end of the file i have thrown the EOF exception to indicate that the file has reached its end.

Program:



import java.io.*;

public class Example1
{

public static void main(String[] args)throws IOException
{
BufferedReader br=null;
try
{
File f=new File("E:/exam.txt");
FileReader reader = new FileReader(f);
br = new BufferedReader(reader);
String strcontent =null;
while(true)
{
if((strcontent=br.readLine()) != null)
{
System.out.println(strcontent);
}
else
{
throw new EOFException();
}
}

}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(EOFException e1)
{
br.close();
System.out.println("The file has reached its end");
}
}
}

Thus in the above code the statement "throw new EOFException()" is used to explicily indicate the end of the file and perform the necessary actions rather than letting jvm to deal with it.

In the above program if you do not include the statement throw new EOFException then it will not get terminated.

Sometimes this exception may occur due to an error in the input file.For eg. if the header of the file indicates that the content length of the file is 1000 characters but if you encounter the EOF character after reading some 200 characters.In this situation EOFException can be used to deal with it.

NOTE:


1.When we use Scanner object to read from a file then java.util.NoSuchElementException is thrown if the end of file (EOF) is reached.
2.If we use BufferedReader object to read from a file then no exception will be thrown upon reaching the end of the file.
3. If we use DataInputStream object to read from a file then this EOFException will be thrown if  the reader has reached the end of the file.

I have also explained, how using DataInputStream Object  to read a file throws the EOFException  in the following program.

Program:

import java.io.*;
import java.util.*;

public class Fileclassread
{
public static void main(String args[])
{
String line;

try
{
DataInputStream in=new DataInputStream(new FileInputStream("Child1.class"));
int bytesavailable=in.available();
System.out.println("Total no of bytes in the file "+bytesavailable);

for(int i=0;i
{
if(in.readInt()==0xCAFEBABE)
{
System.out.println("The minor version number:"+in.readShort());
System.out.println("The major version number:"+in.readShort());
}
}
}
catch(EOFException e)
{
System.out.println("the file has reached its end...");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

output:

Total number of bytes in the file 227
The minor version number:0
The major version number:50
java.io.EOFException
        at java.io.DataInputStream.readInt(Unknown Source)
        at Fileclassread.main(Fileclassread.java:18)

If you see the output of the program,the first line shows how many bytes available in the class file.
Since readInt() will read 4 bytes of data at a time,the for loop should be limited to the value of 55,
because the two readShort() contributes the other 4 bytes.So a total of 224 bytes will be read.

The remaining 3 bytes cannot be read by using readInt() as it requires 4 bytes.Thus java.io.EOFException is thrown.


Three reasons for java.io.FileNotFoundException

File not found Exception

There are three  reason,for this java.io.FileNotFoundException to be thrown at run-time and the reasons are follows:

Reason1: 

 

"If the given file is not available in the specified location then this error will occur".

As you see,this is the most obvious reason for this exception as indicated by the Exception itself.

Example:

import java.io.*;

public class Example1 
{
public static void main(String[] args) 
{
FileReader reader = new FileReader("c:/exam.txt");
BufferedReader br = new BufferedReader(reader);
String strcontent =null;
while ((strcontent = br.readLine()) != null) 
{
System.out.println(strcontent);
}
br.close();
}
}
In the above code during the execution of the line BufferedReader br=new BufferedReader(reader); if the file exam.txt is not found in the given location then the following error message will appear.

Error message:

java.io.FileNotFoundException: c:\exam.txt (The system cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(Unknown Source)
        at java.io.FileInputStream.(Unknown Source)
        at java.io.FileReader.(Unknown Source)
        at Example1.main(Example1.java:9)

This exception can be resolved by giving the correct path of the file or storing the file in the given location.

 Reason 2:


"If the given file is inaccessible, say for an example if it is write protected(i.e, ReadOnly) then you can able to read the file but when you try to modify(write into) the file then this error will occur".

Example:

 
import java.util.*;
import java.io.*;
class ReadingFiles
{
public static void main(String args[])
{
try
{
File f=new File("FileOut1.txt");
PrintWriter p=new PrintWriter(new FileWriter(f),true);
p.println("Hello world");
p.println("HI PEOPLE");
p.println("hello");
p.close();
f.setReadOnly();
PrintWriter p1=new PrintWriter(new FileWriter("FileOut1.txt"),true);
p1.println("World");

}
catch(Exception e)
{
e.printStackTrace();
}

}
}

ERROR MESSAGE:


java.io.FileNotFoundException: FileOut1.txt (Access is denied)
        at java.io.FileOutputStream.open(Native Method)
        at java.io.FileOutputStream.(Unknown Source)
        at java.io.FileOutputStream.(Unknown Source)
        at java.io.FileWriter.(Unknown Source)
        at ReadingFiles.main(ReadingFiles.java:13)

If you see the statements in BOLD in the above program you can able to understand that after setting the readOnly() flag of that file i have tried to write into that file "again". Thus this exception is thrown saying that "Access is Denied". So an important thing to be noted here is if you try to write into a read only file then this exception will be thrown.

 

Reason 3:

 

"In some cases, if the file that you are trying to access for read/write operation  is opened by another program then this error will occur".

Example:


import java.io.*;
import jxl.*;
import jxl.Workbook;
import jxl.write.*;

public class ExcelRead
{
public  static void main(String args[]) throws Exception
{
Cell b[]=new Cell[2];
WritableWorkbook wbook12=Workbook.createWorkbook(new File("ExcelRead.xls"));
WritableSheet sheet=wbook12.createSheet("First Sheet",0);
Label l1=new Label(0,1,"Hello");
Label l2=new Label(0,2,"World");
sheet.addCell(l1);
sheet.addCell(l2);
wbook12.write();
wbook12.close();
}
}

Here what am i trying to do is to write some labels in to the "ExcelRead.xls" file. I thought that this would work fine. But when I execute this program I got this "FileNotFoundException". Later i found that it (ExcelRead.xls) has been opened in MicrosoftExcel Application. So in some cases this kind of errors do occur.

C:\blog>javac ExcelRead.java

C:\blog>java ExcelRead
Exception in thread "main" java.io.FileNotFoundException: ExcelRead.xls (The pro
cess cannot access the file because it is being used by another process)
        at java.io.FileOutputStream.open(Native Method)
        at java.io.FileOutputStream.(Unknown Source)
        at java.io.FileOutputStream.(Unknown Source)
        at jxl.Workbook.createWorkbook(Workbook.java:301)
        at jxl.Workbook.createWorkbook(Workbook.java:286)
        at ExcelRead.main(ExcelRead.java:11).




 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top