What is the exception I should be catching on the dotted line? - java

I have a problem at school. I'm new to programing and I need some help. Please complete the dotted line:
import java.net.*;
import java.io.*
public class Test{
public static void main (String arg[]}
int x=0;
try {
ServerSocket s=new ServerSocket ( k );
s.close();
}
catch (..........................) {x++;}
catch(IOException e) {}
}
System.out.println( "Total "+ x); }
}

Look up in the documentation what exceptions the constructor of ServerSocket can throw and what exception the close function of ServerSocket can throw. One of them is probably IOException, just look up what else.

A hint: if you use a modern IDE, it'll tell you. For example, just write without the try and catch blocks
import java.net.*; import java.io.*
public class Test{
public static void main (String arg[]}
int x=0;
ServerSocket s=new ServerSocket ( k );
s.close();
System.out.println( "Total "+ x); }
}
The IDE will underline the code and give you a suggestion, click on it and it'll insert the appropriate Exceptions automatically.

The answer can be found at the JavaDoc for ServerSocket constructor that you use.

You need to catch (or declare that your method throws) every Checked Exception that is declared by the code that you are calling. These are documented in the JavaDoc and on the method signature. Unchecked exceptions, like IllegalArguementException, do not need to be caught.

To make the code compile, the line should read:
catch (StackOverflowError exc) {x++;}

If you use an IDE, such as Eclipse, you can easily fix those problems and many others, as the IDE will point out exactly what Exceptions need to be caught, saving you from a trip to the Javadoc page which, by the way, is easily accessed directly from the IDE.
#akf: That's not the opinion of the instructors of some major CS schools. For example, the "Introduction to Computer Science | Programming Methodology" course of Stanford uses a modified version of Eclipse. I think it's a much better way to learn a language, avoiding those situations where you are fixing a problem, compile, and then fix the new problem. This can be frustrating to newcomers. An IDE is just a tool to aid programming, it doesn't cause dependence, and it certainly won't stop you from coding without it.
I do agree, however, that it's important to know the basics, as far as using java or javac is concerned, just in case you ever find yourself with a terminal in front of you.

As you mention in your comment on Henri, you have to choose between either SecurityException or IllegalArgumentException.
The significance here lies in the variable x. What is x supposed to count? My guess would be the former, but there should be a hint in your assignment.
(BTW: I only see a mention of SecurityException besides IOException in the documentation)

Related

How to make java recognize unreachable code and stop with compile errors

I'm working in a big legacy project and I'm still learning about clean code in java and trying to apply some good manners that I already know. Nevertheless, I tried to write a method like I write in others languages (like Rust), avoiding unnecessary variables, etc...
But in this case below it can't compile it without the unreachable return null outside the try-catch block.
private Inet4Address setServerAddress() {
try {
if (somethingTrue()) {
return (Inet4Address) Inet4Address.getByName("127.0.0.1");
}
return (Inet4Address) Inet4Address.getByName(getIP4());
} catch (UnknownHostException e) {
System.out.println("Error at getting the server address from " +
"command line. (" + e.getMessage() + ")");
System.exit(1);
}
/* Unreachable */
return null;
}
I choose to use the System.exit(1) because as this is the terminal part of the application, I wouldn't like to see a big java exception message, but only something that made sense for the user.
So my question is, how can I make javac understand that there isn't any case that this function won't return something. I really don't like to keep a return null in my code, even if it will never run.
Calling System.exit() down in the bowels of your code makes it hard to reuse this method.
I would have this method throw an exception (you can simply not catch the UnknownHostException) and have a try-catch at the top level of your tool (I'm assuming that "this is the terminal part of the application" means that this is a command line tool?), probably in your main method.
That allows you to put a standard way of handling all run time errors in a single place.
The exception could be an unchecked exception, or if you want to make the API clearer, make a new checked exception.
any advanced IDE such as Eclipse can show unreachable code as a warning after compilation that shows up in Problems tab. In addition a Eclipse SpotBug plugin static analysis tool can find more sophisticated cases.

What does it mean by saying "It is impossible to recover from errors" in java? [duplicate]

This question already has answers here:
Can the JVM recover from an OutOfMemoryError without a restart
(7 answers)
Closed 6 years ago.
Here says that it is impossible to recover from errors.
I am not sure what does it mean because I can catch Error just like Exception.
Eg:
public static void main(String args[]) {
while (true) {
try {
throw new StackOverflowError("stackoverflow");
} catch (Throwable throwable) {
//do something
}
//program recover and continue to execute
}
}
The above program execute normally and It seems that It's possible to recover from errors. Can anyone help?
UPDATE:
example of stackoverflow is a little puzzling, only idiot want to recover from stackoverflow. Here is another example about OutOfMemory:
public class Main {
public static Map<Long, Object> cache = null;
public static void main(String args[]){
while(true){
try {
if(cache == null) {
cache = new HashMap<>();
}
for (long i = 0; i < Long.MAX_VALUE; ++i) {
cache.put(i, i);
}
}catch(OutOfMemoryError error) {
cache.clear();//delete some unused entry or clear all.
cache = null;
System.gc();
System.out.println("release memory");
}
}
}
}
It's a simple HashMap cache, execute the code using java -Xmx1m Main , and we will see an OutOfMemoryError soon, then release memory manually, and the program will continue to execute. insert-> OutOfMemoryError -> release -> insert...
See? the program have recovered from an OutOfMemoryError. Isn't it? And I think it's meaningful. So, Why someone still said program can't recover from OutOfMemoryError.
Obviously, the mere ability to "catch" an exception does not mean that you will (always ...) be able to "recover from" it ...
... i.e.: "to sally forth, entirely unscathed, as though 'such an inconvenient event' never had occurred in the first place."
I think that the essential point of the original author is more-or-less that: Even though the poor souls on the Titanic might have "caught" the fact that their ship was sinking, there was nothing that they could do to "recover" the ship and to sail it on unscathed to New York.
--- Edit:
"Now, let me add one more thought!" (As other Answerers have also done here.) Sometimes, an Error Exception is intentionally "thrown" in some block of code that has intentionally been surrounded by a catch-block.
Maybe the error (which is itself "an object") is of a particular user-defined type that the catcher will recognize. (He can "re-throw" any that he does not recognize, or simply decline to catch it.) This can be a very elegant and efficient way to handle, well, "the exceptions to the rule." (Hence the name...)
Whenever a block of code encounters a situation that "only happens once in a blue moon, but it just did," it can throw an exception high into the air, knowing that the nearest catcher will catch it. This catcher, in turn, can recognize the thing that just landed into his baseball-mitt, and respond accordingly. There can be any number of "catchers" out there, looking for different things.
This strategy is not "an Error," but rather an intentional alternative flow-of-control within the program.
Consider the following code which actually throws a StackOverflowError
public class Code
{
public static void main(String[] args)
{
try
{
f();
}
catch (Throwable t)
{
System.out.println("OK I'm recovered, let me try that again");
try
{
f();
}
catch (Throwable t2)
{
System.out.println("What's going on here??");
// let me try one more time..
try
{
f();
}
catch (Throwable t3)
{
System.out.println("Why can't I really recover");
}
}
}
}
// Bad recursion...
private static void f()
{
f();
}
}
Do you really want to continue with execution knowing that your code has such an issue? What if you need to call f() again somewhere down the line? You would want to have such code in production that tries to continue if a method keeps giving a StackOverflowError?
You're just catching the Throwable here, before it ever gets to the point where it's an error. Throwable is the superclass of both errors and exceptions. Therefore, a Throwable is not comparable to an error itself, much less a StackOverflowError, and your program is not recovering from an error.
An exception is sort of like a misdemeanor charge. It's not a fantastic thing to happen to you, or rather, your program, but it definitely won't land you in jail for extended periods of time. However, an error is dangerous - it is on the level of a felony, to continue this analogy. Java is considered safer than, say, C, because it will tell you when you are doing something that is unsafe. C, on the other hand, will allow you to access data that is beyond the scope of an array, for example, and you'll get awful bugs that are very difficult to debug that way.
The analogy to crime ends after that point. If you had scrolled down a little further on the page that you linked to, it continues to delineate the reasons why exceptions and errors are different, namely, that "errors are caused by the environment in which the application is running," and therefore, because your application is only in charge of itself, and not the actual environment, it cannot of its own volition recover from an error.
The page also gives the example of an OutOfMemoryError. While you, as the programmer, can plan ahead to try to prevent an OutOfMemoryError by making your code as efficient as you can, you won't be able to prevent such an error if the code is run on a machine that has, say, 1 byte of RAM. Errors cannot be caught because they are (mostly) out of the hands of the application itself. It's up to the programmer, such as in Michael Markidis' example, to not cause an error and avoid any error-causing programming techniques (such as using "Bad recursion") that will crash your program.

How to avoid try-catch when validating text input

While working on a code, I was wondering if I could avoid try n catch and used something else. For example, if i have a value(from console) of type double and if user enters a string or something else then there should be a prompt to re-enter the value.
I know this can be done very easily using try-n-catch but how can we do it without it, is there any way out?
Please give an example if possible.
Sadly, the JDK lacks the TryParse method that some other libraries provide. I wouldn't be surprised to find something in Apache Commons or Guava that does it.
Alternately, you might use a Scanner and use its hasNextDouble to do the check.
If you're asking how to avoid dealing with exceptions in general: Don't try. Exceptions are a powerful way of handling exceptional conditions in programs, and the "handle-or-declare" provided by checked exceptions (e.g., your code must handle the exception, or declare that it doesn't) is very useful.
But there are some use-cases, like your example, where you might well want to avoid an exception being thrown because, after all, a user entering invalid input isn't an exceptional condition, it's an all-too-common one. :-)
Throw Exceptions are less robust but a good way to deal avoiding with try/catch statements.
import java.io.*;
public class UsingThrows {
public static void main(String args[]) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("def.txt");
System.out.println("OK 1");
}
}

throw user defined exception in single statement in java

Recently i attended an interview. one of the questions asked in technical interview round is "how can you throw a user defined exception using single statement".
i wrote the code as
class MyException extends Exception{
public MyExeption(String err){
super(err);
}
class sample{
public static void main(String a[]){
throw new MyException("Error");
}
but he said that i used 2 statements 1 for throw statement and other for super() statement.
what is the answer. plese clear my doubt. thank you
I am sure that the interviewer was looking for you to extend Exception anonymously:
throw new Exception("Error") {
// Here is what makes the exception user-defined.
// You do not need to override anything, but if you want, you can:
public String getMessage() {
return "Here is your user-defined exception!";
}
};
Literally, the question asks to throw. Not to declare & throw.
throw new MyUserDefinedException("It was declared elsewhere.");
If you want to declare & throw, that's what the other answer said. Of course this is complete crap code with no purpose. I would penalize or fire somebody, who used this kind of approach in real work.
throw new IllegalArgumentException("BS interview question, take another job."){};
It also doesn't work, over RMI :( The worst thing is, how many days of debugging ($1000s..) it will take to uncover it again, if some twit ever writes this bug for you.
They may be testing your Java understanding, but it seems likely these clowns don't actually know how to use/ what to do with Java themselves.
My interview questions ask actual real business questions. They can be highly challenging.
I don't look for idiots who can do stupid pointless things within the language idiom, I look for people who can solve not-easy problems within a typical business application.

Choose and test java decompiler [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Now I'm trying to find the best java decompiler, I found these:
http://java.decompiler.free.fr/
http://www.reversed-java.com/fernflower/
http://dj.navexpress.com/
http://cavaj-java-decompiler.en.softonic.com/
With these decompilers I handle byte code of this class:
public class ss
{
public static void main(String args[])
{
try{
System.out.println("try");
}
catch(Exception e)
{
System.out.println("catch");
}
finally
{System.out.println("finally");}
}
}
and I got the following results:
fernflower:
public class ss {
public static void main(String[] var0) {
try {
System.out.println("try");
} catch (Exception var5) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
}
DJ Java Decompiler:
import java.io.PrintStream;
public class ss
{
public ss()
{
}
public static void main(String args[])
{
System.out.println("try");
System.out.println("finally");
break MISSING_BLOCK_LABEL_50;
Exception exception;
exception;
System.out.println("catch");
System.out.println("finally");
break MISSING_BLOCK_LABEL_50;
Exception exception1;
exception1;
System.out.println("finally");
throw exception1;
}
}
cavaj:
import java.io.PrintStream;
public class ss
{
public ss()
{
}
public static void main(String args[])
{
System.out.println("try");
System.out.println("finally");
break MISSING_BLOCK_LABEL_50;
Exception exception;
exception;
System.out.println("catch");
System.out.println("finally");
break MISSING_BLOCK_LABEL_50;
Exception exception1;
exception1;
System.out.println("finally");
throw exception1;
}
}
http://java.decompiler.free.fr/:
import java.io.PrintStream;
public class ss
{
public static void main(String[] paramArrayOfString)
{
try
{
System.out.println("try");
}
catch (Exception localException)
{
System.out.println("catch");
}
finally {
System.out.println("finally");
}
}
}
I see that the best result in decompiler: http://java.decompiler.free.fr/
To test, I wrote very simple code. What do you think, what code to write to test decompilers? Maybe the idea is to better than a try{} catch(){} finally{}?
The code that you use to test should test the features available the in JDK used to compile the target class. For example, if you know that your target is written in Java 1.5, it is reasonable to assume that the code might include generics, so you will want to make sure that your chosen decompiler handles them properly. In my experience, the freely available decompilers tend to lag behind the JDK releases in terms of the features they support by 1-2 releases.
Based on personal trial and error, JD tends to do the best job in general. However, if you're decompiling code that was written in 1.3 or lower, I'd also suggest you give JODE a try.
EDIT, 5 years later:
CFR, Procyon, and Fernflower lead the way in this space.
Procyon has it's own comparison.
I have been using http://java.decompiler.free.fr/ for a long time now and found it to be the best one. In particular I used it to decompile a third-party jar and I was able to modify the source code as well with it.
Its easy to use and the UI is also neat and clean.
Update: Java Decompiler is no longer available on http://java.decompiler.free.fr/. It has new link http://jd.benow.ca/ from where it can be downloaded.
If you anticipate to get any meaningful results, you really should test with a bit more non-trivial code. Fernflower was created with the aim of handling highly unusual and obfuscated bytecode. Thus decompiling such simple snippets is no big deal. By the way, if you are interested in testing the stand-alone version of Fernflower drop me a note at fernflower(dot)decompiler(at)gmail(dot)com. Version 0.8.4 is now in semi-public beta (however not available on the website yet).
It looks like fernflower and JD Java Decompiler are producing decompiled code that is as good as is possible for this particular testcase. The other two aren't doing a good job, IMO.
What do you think, what code to write to test decompilers?
Write more complicated code using all available constructs.
Try them out on some real code.
Try them out on some real code that has been obfuscated.
When trying out code that you compile from source, experiment with different "-g" options, and with different Java compilers.
http://www.reversed-java.com/fernflower/, see my comparison on github.com /vorburger/ScratchApplet
For information, JD supports switch(enum), switch(string), assert statements and for-each loops.
About the -g(javac) options,
if you omit the line numbers, JD can
not reconstruct the original flow of
instructions : the types of loop can
not be determinate, the multiple
assigments can not be regenerate, and
the algorithm used to realign source
code can not work.
if you omit the
local variable data, JD can not,
sometime, determine the exact range
of variables. It's problematic.
Ok, this is written from my mobile phone so bear with me.
1st of all, every java file codes are compiled in bytecode in their respective .class file. This means that constants are stored AS IS (hence strings can easily be retrieved) and variables are assigned to a register that is then put on a stack program execution when the JVM process the class file.
The reason your exception block are not returned to the original code you've written is because of the way javac compiled & translated the code to java bytecode.
If you want to know which decompiler works best, write all java well known statements (for loop, if statement, while loop) with some expressions & see what best represent your original code.
Good luck.
It's been a while since any feedback to this thread. However since I found it and took the input seriously I feel it important to give an update.
I have used Java Decompiler Free with good success. However, recently I accidentally deleted quite a bit of code of a production J2EE application. assumed JD Free would handle it, but it doesn't handle generics at all. Plus there was code where it handled variable initialization totally wrong. What I ended up with was a total mess.
There may not be anything out there that will to the job correctly. In my case it's just another lesson in backup, backup, backup. I need a de-compiler that handles generics properly in order to do a mass recovery. But some accuracy of handling variables would also help. It is too much to ask a tool to spit out the original code. But what I have seen so far will compile but will not function properly, generics aside. So I suppose it's going to be a long week before Christmas!!

Categories

Resources