Exceptions package location in Java - java

Why some exceptions are located in their respective packages (like IOException, located in java.io) but others are in java.lang (like ArrayIndexOutOfBounds in java.lang). Is this because one is checked and other is Unchecked Exception?

I really don't think that base on checked and unchecked conditions java exceptions are located in respective packages.If we consider about java.io package and java.lang packages,
java.io package contains classes for system input and output through data streams, serialization and the file system.And also handling files also done by Java I/O API.
java.lan package contains all the classes that are using to the design of the Java programming language such as String, Math. And provide basic runtime support for threads and processes.
Java IOException is thrown whenever an input or output stream is interrupted.So this regarding System input and output.So this IOException class must come under java.io package.
Java RuntimeExceptions such as ArrayIndexOutOfBoundEceptions are checked at the runtime.java.lan package support to handle runtime threads.It's include classes that support runtime for threads and process.
So IOException,ArrayIndexOutOfBound are classes with relevant function.So those classes must be categorized under relevant packages.

First: ArrayIndexOutOfBoundsException is not inside java.lang.Throwable. It is inside the package java.lang. It is a subclass of java.lang.Throwable, but so are all exceptions (including IOException).
ArrayIndexOutOfBoundsException is inside java.lang because all the "basic stuff related to the core language" is in java.lang, and ArrayIndexOutOfBoundsException is "basic stuff related to the core language".
IOException is inside java.io because all the stuff related to I/O is in java.io, and IOException is "stuff related to I/O".
There is no deep or interesting technical reason.

As a general rule, it is a good idea to place checked exceptions near the code which is throwing those types of exceptions. This explains your first observation. On the other hand, the exception ArrayIndexOutOfBounds is an unchecked runtime exception. It is associated with a type of runtime error from which the program is generally not expected to recover. As such, it placed in java.lang.throwable with other similar runtime exceptions. So as a general rule, if you define custom exceptions for your program, you should therefore probably put them in the packages, or near the code, which uses them.

Related

Does java classloader validate method body?

For Java compiler to resolve reference to another class in different file needs to be on classpath.
I know that if the class is not found on the classpath or the method signatures do not match some Exceptions are thrown.
However, is there any validation that compares compile time classpath with runtime classpath when it comes to method implementations?
What If I provide classpath with method signatures matching the ones during compile time but with different implementation.
Will there be no Validation error or any Exception thrown? That seems very insecure.
Generally speaking, no, as long as the signatures match some JVMs can even replace methods at runtime (modulo some additional constraints).
Of course a custom classloader implementation could perform extended validations, such as checking hashes/signatures.
What the JVM does validate is the standards-conformance of the bytecode. I.e. bytecode cannot reference nonexistent stack slots, do arbitrary jumps or similar things that would lead to illegal behavior inside the JVM.

Java Path Finder for Bytecode Verification in an existing project, Bytecode Verification

I'm trying to use JPF to verify my bytecode generated while runtime with javassist.
The code I'm trying to verify is supplied by the user while my program is running. As I can't check all OOP models and stuff like that I need a verification process before running his code.
At the moment I simply generate bytecode with javassist from his classes.
My problem now is that I get exceptions sometimes because the user did some inheritance mistakes and stuff and my application shuts down with an exception cause I tried to load and execute his classes.
Therefore I would like to verify that generated bytecode in runtime to avoid such exceptions and to know earlier if the classes supplied from the user are faulty (or contain any problem).
Is this possible with JPF while in runtime?
Any other solutions on this?
Thanks!
As JPF uses BCEL Stand-alone Bytecode Verifier might be helpful. Just programmatically invoke the Verifier class - or even dive into the details of this class.
hth
There are many points to check:
the bytecode itself according to the class file format
the runtime phases: loading, linking and initializing
From my point of view, a ClassLoader does all that steps but it generally loads one Class at a time, and only on demand.
In your context, I propose you write a ClassLoader that loads in sequence all classes from generated bytecodes and reports each failing class name with caught exceptions. The ClassLoader is instantiated with the reference to the relevant parent ClassLoader and is discarded after the test passed, the generated bytecode is then loaded by the original ClassLoader of your runtime context.
Probably this class loading check may be implemented thanks to OSGi but it will require more efforts than a standalone ClassLoader.
If you don't have an absolute requirement to use JPF, the ASM library includes CheckClassAdapter which can verify byte code. It is only a sanity check however - I don't believe it will catch problems with inheritance etc.

How to find all locations in a Java project where a RuntimeException is possible to be thrown?

I have a java project and I want a list of locations in source code where a RuntimeException might be thrown. Is there any tool or Eclipse plugin to do this?
With FindBugs or PMD the NullPointerExceptions might be located, but I need to locate others as well.
NullPointerException, ClassCastException and ArithmeticException are a special cases as they do not need to be explicitly thrown. However, everything else has to be thrown explicitly.
Searching for possible causes of NullPointerException is useful as its a common bug, however like all RuntimeException they are best avoided rather than handled. Searching for all possible causes is likely to give you a very large result which is unlikely to be useful. (I have been through this exercise myself and after lots of work didn't achieve much IMHO)
You are better off using code coverage and try edge case values to ensure you have good test cases which are likely to trigger all possible exception instead.
If you're only checking your own code, you can do this with Checkstyle. Look at the Coding Problems, Illegal Throws check.
You can specify any number of Exceptions, by default it is: java.lang.Throwable, java.lang.Error, java.lang.RuntimeException.
Note: This doesn't pick up subclasses of the above exceptions, it only picks up the classes themselves. It also does not check source code to which you don't have access, so runtime libraries won't be checked, for instance.
I do agree with the other answers. Since I don't know what you want to achieve, I want to offer a more direct answer to your question:
Unfortunately I know no tool that does this. Sorry. Depending on how important it is to you, you could invest some work yourself.
Check your code 'by hand'.
After that the JDK remains (and most likely some libs you are using). You can download the JDKs source code from Oracle. Than you can do a full text search for the occurrences of newly created exception instances again. Note, however, that even this tedious work will not give you all possible sources since some methods are missing there.

Differences between NoClassDefFoundError and ClassNotFoundException?

NoClassDefFoundError extends LinkageError which in turns extends Error.
Javadoc for Error class states:
An Error is a subclass of Throwable
that indicates serious problems that a reasonable application
should not try to catch.
Class loading methods like Class.forName() only declares ClassNotFoundException in throws clause. Which, in addition to above description of Error means that we should not be usually catching the NoClassDefFoundError when loading classes with Class.forName() etc.
My question is what are the conditions in which NoClassDefFoundError is thrown instead of ClassNotFoundException?
ClassNotFoundException is more likely to be thrown (to your code) in situations where you're manually loading classes - precisely for things like Class.forName(). These names may come from user input, for example.
NoClassDefFoundError will occur when a class file itself refers to a class that then can't be found. The class was present at some time, but now isn't - this isn't just a bug in the code that's trying to do reflection, it's a deployment mistake of not making all the required classes available. As far as I can tell a NoClassDefFoundError will usually or possibly always wrap a ClassNotFoundException - but the point is that this isn't something your code is meant to guard against, as it indicates an environment which is probably too broken to recover from.
At least, that's my understanding :)
NoClassDefFoundError occures at runtime because compiler not able to find .class file.

Can i deny access to a jvm class by configuring java.policy file?

I wanted to add to my jdk6\jre\lib\security\java.policy file an interdiction to create some classes that are blacklisted by appengine. For example I want my local jvm to throw an exception when the application tries to instantiate javax.naming.NamingException.
It is possible?
I will try to explain my specific problem here. Google offers an service (GAE-google app engine) that has some limitations on what classes can be used. For example doesn't instantiate JNDI classes that are in javax.naming package. They also offer an testing server that can be used to tests this application on my machine, but this server allows such classes and can exacute the code. You find out that you used a blacklisted class only after you upload your application to google. I was thinking if such class blacklist enforcement couldn't be done on the development jvm. Else i'm thinking that this would be easy they might already provide such a policy file.
You could write a small loader application that creates a new, custom classloader. Your application classes could then be loaded using this classloader.
In the custom classloader, you can then throw ClassNotFoundException when your application tries to access a class that you want to blacklist.
You will need to overload the load() method. This method will be responsible for throwing the exception on your blacklisted classes ordelegating to the parent Classloader if the class is allowed. A sample implementation:
public Class loadClass(String name) throws ClassNotFoundException {
if(name.equals("javax.lang.ClassIDontLike")){
throw new ClassNotFoundException("I'm sorry, Dave. I'm afraid I can't do that.");
}
return super.loadClass(name, false);
}
(Of course, a real implementation can be way more sophisticated than this)
Because the classes of your application are loaded through this Classloader, and you are only delegating the loadClass() invokations to the parent classloader when you want to, you can blacklist any classes that you need.
I am pretty sure that this is the method that Google uses to blacklist classes in their server. They load every app in a specific Classloader. This is also similar to the way that Tomcat isolates the different Web Applications.
Wouldn't you rather get compilation errors than runtime errors while testing your program? You could configure your IDE or compiler to warn you when an undesired class is instantiated. I know AspectJ has some nice features for this: You can define compilation warnings/errors on join points and get feedback in e.g. Eclipse. To use this in Eclipse, you simply install the AspectJ plugin and write a suitable aspect. To get the errors while compiling from a command line or script, you would actually have to use the AspectJ compiler, but I doubt that you would need that.
The Java documentation lists all possible policy permissions here:
http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html
Class creation / loading is not mentioned, so I believe you cannot enforce this using a policy.
At any rate, why do you want to throw an exception when an exception class is loaded? Maybe you could explain your problem, then someone might be able to propose a solution.
Edit:
One way to prevent loading of certain classes would be to remove them from the JRE installation. Most system classes are contained in rt.jar in your JDK/JRE installation. You should be able to modify it with any ZIP-tool.
Just create a special installation of your JRE, and modify its rt.jar. That is an ugly hack, but should be OK for testing purposes...

Categories