"Given that FileInputStream’s constructor throws FileNotFoundException, which is a subclass of
Exception, write the header for a public method named process that takes a String parameter
and returns nothing, and whose body instantiates a FileInputStream object and does not contain
a try-catch statement."
I know it's a too-simple question but I want to make sure I'm not messing up in a dumb way. Also, not sure whether to use FileNotFoundException or just Exception or IO, etc.
public process(String file) throws FileNotFoundException {
FileInputStream file = new FileInputStream("stuff.txt");
}
What you have for the throws clause is good. Throwing IOException would not be terrible, but it's better to be specific. Calling code can still treat it as an IOException.
Generally you shouldn't throw Exception except for special cases (Junit methods and similar situations where everything thrown will get caught by an exception handler), because it forces everything that calls it into the position of either handling Exception (where it may not be the appropriate place to do it, it is better to let most exceptions bubble up to one place where they can get handled uniformly) or also throwing Exception, which then puts other calling methods in the same position.
Your method declaration is not valid because there's no return type. Methods that don't return anything are declared with a return type of void.
Using the same name for a method parameter as for a local variable will not work, you should make those different. The constructor call should take the method parameter as an argument (instead of hard-coding a string literal). (+1 to geceo's answer for pointing that one out, I had missed that one.)
As a suggestion, your code would be clearer if it used names that reflected the contents of the variables. Calling a FileInputStream file is not clear, it would be better to call it inputStream. Calling a String file is not clear, it would be better to call it filename.
What you have is fine (except you're missing the void return type).
Always throw (and catch) the narrowest specification of Exception you can (in this case FileNotFoundException).
As spotted by Nathan, you forgot to declare that process returns nothing, that is, you forgot the void keyword.
There's another problem with your parameter String file ("duplicate local variable file"). You should rename it String filename and pass it to the constructor of FileInputStream:
public void process(String filename) throws FileNotFoundException {
FileInputStream file = new FileInputStream(filename);
}
About the general topic, you always have to make a choice when you call a method that throws exception(s):
You can use a try/catch block and deal with the error in your calling method (log them, for example);
or
You can propagate the exception using the throws keyword in your method declaration.
So what you're doing here is the second possibility.
Also add void as the return type. Rest is fine.
public void process(String file) throws FileNotFoundException {
FileInputStream file = new FileInputStream("stuff.txt");
}
You can do few things to make your method better by buying insurance against accidental misuse:
public void process(final String file) throws FileNotFoundException {
final FileInputStream inputStream = new FileInputStream("stuff.txt");
//invoke operations on inputStream object
//After 100 lines of code
inputStream = new FileInputStream("foo.txt"); // compile error
}
Observe the final keyword next to parameter passed to method and FileInputStream object reference.
Related
To be clear: I have an object which is continiously changing its values during the runtime and I want to save the created and modified object on a file.
I found how to that and I found also how to read back the object saving it into one another. But the question is: is it possible to call the class constructor of my object with the only parameter of the file in which the object I want to retrieve is stored?
NeuralNetwork(File fs){
ObjectInputStream ois;
changeFileSave(fs); //just sets the file as savefile for the future
try{
ois = new ObjectInputStream(new FileInputStream(_saveNet)); //_saveNet = fs
this = (NeuralNetwork) ois.readObject();
}
catch(Exception e){
//error message
}
}
It gives me an error on 'this ='
If it's possible how do I do something like this?
Thank you
The keyword this is a read-only reference, you can never write this = even in the constructor. Moreover, the constructor in java does not return anything.
You would have to take the object you've read and map its properties one by one (or using reflection) to the properties you have in the object you're instantiating.
However, I would submit that by passing a file to a constructor and doing the IO in it you are violating separation of concerns. By writing things this way, you have forever tied a neural network to a File, with a whole host of attendant issues, including (not limited to) the fact that you may be storing your values elsewhere at some point.
IMO you are better off using a factory pattern to build your object and making your NeuralNetwork object a plain object. Then the ambiguity disappears because your factory method can simply return (NeuralNetwork) ois.readObject();
this = (NeuralNetwork) ois.readObject();
Consider this as a hidden final argument that points to the instance that is executing the method. Its value cannot be changed. If you want to make a variable point to an instance, there's no problem with that, as long as you don't use this.
What you want to do is more appropriate for a factory or factory method than for a constructor. Use one of this patterns (or a static method if you want to keep it very simple) to create your instance from the file. Not sure if you need many instances of that class, but if you only need one, you should consider using a Singleton getInstance() method instead the previously mentioned.
You can't assign this, since it is readonly. this always points to the instance itself and is used throughout the life of the object to access its methods and attributes.
If you want to create an instance of your NeuralNetwork class by reading data from a file, you could use a factory method:
public class NeuralNetwork {
private NeuralNetwork() { // private constructor forces us to use the
} // factory method to create instances
public static NeuralNetwork loadFromFile(File fs) {
ObjectInputStream ois;
this.changeFileSave(fs); // just sets the file as savefile for the future
try {
ois = new ObjectInputStream(new FileInputStream(_saveNet));
return (NeuralNetwork) ois.readObject();
}
catch(IOException e){
throw UncheckedIOException(e);
}
}
// other methods and attributes
}
Then, wherever you use your NeuralNetwork class and need an instance, use:
NeuralNetwork network = NeuralNetwork.loadFromFile(someFs);
// use network instance and have fun with it here
Note 1: I've defined a private constructor to force everyone use the loadFromFile factory method to create an instance. This means that this class can only be created from within a static method of this class.
Note 2: I've also rethrown the exception with an unchecked exception. This is personal taste. I wouldn't just log the exception and go on. Instead, I would throw the exception so that the caller handles it properly, because it doesn't make any sense to go on if an instance of the class hasn't been created. If you don't want to rethrow the exception as an unchecked one, just don't catch the original IOException and add a throws IOException clause to your factory method. This would force the callers of loadFromFile to catch the IOException and handle it.
I have been working with a library and I notice the following construct.
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
I am having difficulty in identifying if it is an anonymous class as I don't see it using the interface or concrete class.
Or is it a just a normal method that does a throws IOException.
I am coming from a different programming background and looks kind of strange for me.
Are you forced to use throws ?
If you are asking about the presence of throws IOException, you must declare it using the throws keyword, because it is a checked exception.
So basically
String run (String url) throws IOException { ... }
^ ^ ^ ^
method method param type marks checked ^
return type name and name exceptions the method body
method may throw
Basically, checked exception in Java is any subclass of Throwable which does not inherit from RuntimeException or Error. Whenever your code throws a checked exception, the Java compiler forces you to either catch it or declare it using the throws keyword.
Checked exceptions allow you to verify at compile time that you are either handling exceptions or declaring them to be thrown: When you call a method like run(), the compiler will warn you that you must do something about it (catch or declare). For some explanation why Java enforces this, see e.g. this question on SO.
The article linked above explains what is the semantical difference between checked (e.g. NullPointerException) and unchecked exceptions (e.g. IOException)
Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time
Checked exceptions represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
It is a method.
The signature of the method is String run(String url) throws IOException. It means that the method name is run; that the method take a String as argument; return another String and may throw an IOException.
This question already has answers here:
throw new Exception vs Catch block
(5 answers)
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 9 years ago.
I noticed that both of these, for example, are working:
public void func(int a) throws IllegalArgumentException {
if(a < 0)
throw new IllegalArgumentException("a should be greater than 0.");
}
public void func(int a) {
if(a < 0)
throw new IllegalArgumentException("a should be greater than 0.");
}
It makes me to ask:
When should I announce throws anException, and when not, and just throw it without declare about it?
Checked exceptions must be always written in the method signature that it throws.
If the exception extend RuntimeException, you don't have to write throws in the method name, but it's highly recommended since it's clearer and it'll be mentioned in the documentation of the method.
/**
* #throws This won't appear if you don't write `throws` and this might
* mislead the programmer.
*/
public void func(int a) throws IllegalArgumentException {
if(a < 0)
throw new IllegalArgumentException("a should be greater than 0.");
}
The beauty with Throws is that the Exception converts into Checked Exception thus every time any developer will try to use the first approach he will be warned to place a try-catch block before calling the method which has Throws in its Signature.
From the JLS section 11.2:
The Java programming language requires that a program contains
handlers for checked exceptions which can result from execution of a
method or constructor. For each checked exception which is a possible
result, the throws clause for the method (§8.4.6) or constructor
(§8.8.5) must mention the class of that exception or one of the
superclasses of the class of that exception (§11.2.3).
so briefly, you need the throws statement if an exception is checked. If you have an Exception, and it's not a subclass of RuntimeException, then it's checked.
IllegalArgumentException is a subclass of RuntimeException, and so it's unchecked, and you shouldn't need to declare it in a throws statement. This is true of most exceptions like this (IllegalArgumentException, NullPtrException etc.) since you can't reasonably be expected to handle these easily.
When your exception is checked you are obliged by the compiler either to catch the exception or announce a throws declaration.
Check this post for a comparison of checked vs unchecked exceptions.
This is because IllegalArgumentException extends RuntimeException. You can't leave the throws clause in below like case.
public void func(int a) {
if(a == 0)
throw new Exception("a should be greater than 0.");
}
There have been many technical answers that are JLS Section 1.2, Checked exceptions etc which explains the use of it.
But your question
When should I announce throws an Exception, and when not, and just throw it without declare about it?
If your code is generating some explicit exception and throwing it, then you should always add throws clause and you should generate documentation by just writing /** above the function which will generate the documentation tags for you. This will help all the other users who use your library or functions that the certain function or constructor is bound to throw an exception if some invalid arguments or some values have not been initialized prior to call of this function.
Example,
/**
*
* #param filePath File path for the file which is to be read
* #throws FileNotFoundException In case there exists no file at specified location
* #throws IllegalArgumentException In case when supplied string is null or whitespace
*/
public static void ReadFile(String filePath) throws FileNotFoundException, IllegalArgumentException
{
if(filePath == null || filePath == "")
throw new IllegalArgumentException(" Invalid arguments are supplied ");
File fil = new File(filePath);
if(!fil.exists()|| fil.isDirectory())
throw new FileNotFoundException(" No file exist at specified location " + filePath);
//..... Rest of code to read file and perform necessay operation
}
These documentation tags and throws are moreover to make the programmer life easy who will reuse your code and will know in advance that IllegalArgumentException, FileNotFoundException will be thrown if function is invoked with wrong parameter or file is not available at specified location.
So if you want that your code and functions are self explanatory and provides all necessary cases what exceptions are thrown then add the following clauses otherwise it is your choice.
Remember, if after 30 days if you yourself are using (I am sure you are going to re-use it near future) those function then it will be much more helpful and you will exactly know just by those clauses what I did in that function.
While you need to declare the checked exceptions,
Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor .. from - http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
I am trying to execute below written code and the code should throw an exception but it isn't doint it
try {
Field.class.getMethod("getInt", Object.class).setAccessible(false);
StringSearch.class.getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.getClass().getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.searchChars(cc,pattern3);
ss4.searchString(str,pattern);
}
catch(NoSuchMethodException ex){
ex.printStackTrace();
}
it should actually throw IllegalAccessException.
ss4 is an object of class BNDMWildcardsCI (one of the algo for String search)
cc, pattern3 are character arrays
str, pattern are Strings
why it isn't throwing an exception, it is not throwing the NoSuchMethodFound exception means that it is able to find the method also i tried to print the isAccessible and it says false
but when i run the tests it doesn't throw any exception
To the best of my knowledge, if a method is declared public (or otherwise accessible), setAccessible(false) can't make it private. It's only useful if you have a private method and you previously called setAccessible(true).
The method setAccessible(boolean) work on object reflect not on normal object. In your code you set it on a method object not on the ss4 object.
To show my point:
Class<?> clazz = ss4.getClass();
Method searchCharsMethod = clazz.getMethod("searchChars",cc.getClass(),pattern3.getClass());
searchCharsMethod.setAccessible(true);
You have set the accessible flag to false on object assigned to searchCharsMethod not ss4.
As bonus see what happen when you call
searchCharsMethod.invoke(ss4,cc,pattern3);
For more please read the documentation
I have to throw an IOException using Mockito for a method, which is reading an input stream like given below. Is there any way to do it?
public void someMethod() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
firstLine = in.readLine();
} catch(IOException ioException) {
// Do something
}
...
}
I tried mocking like
BufferedReader buffReader = Mockito.mock(BufferedReader.class);
Mockito.doThrow(new IOException()).when(buffReader).readLine();
but didn't work out :(
You're mocking a BufferedReader, but your method doesn't use your mock. It uses its own, new BufferedReader. You need to be able to inject your mock into the method.
It seems that inputStream is a field of the class containing this method. So you could mock the inputStream instead and make it throw an IOException when its read() method is called (by the InputStreamReader).
You can't mock BufferedReader here since it's being created inside the method.
Try mocking inputStream and throwing the exception from InputStream.read() instead.
The way that I would recommend is to have an extra class that looks after the creation of the BufferedReader. This class has just one method, with no actual logic in it, so it doesn't need any unit tests.
public class BufferedReaderFactory{
public BufferedReader makeBufferedReader(InputStream input) throws IOException{
return new BufferedReader(new InputStreamReader(input));
}
}
Now, add a private field of type BufferedReaderFactory to the class that you're testing, along with a means of injecting it - either a setter method or an alternate constructor. In the standard constructor for your class, instantiate a BufferedReaderFactory and set the field accordingly. In your someMethod(), call the makeBufferedReader() method on the field, instead of using new.
Your class is much more testable; because now, you can write a test that injects a mocked BufferedReaderFactory to the object that you're testing, before calling someMethod(). On that mock, you can stub the makeBufferedReader method to throw the exception that you want.
Please add a comment if you want me to go into more detail on any of the steps above. You might also like to read my post on mocking object creation on the Mockito wiki; which is closely related to this.
But the most important message is that making your classes testable is really important, and you will reap the benefits of doing so many times over.