unreported exception java.io.IOException - java

What's wrong with this code
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* #author Master
*/
public class Server {
try
{
ServerSocket S = new ServerSocket(3333);
Socket So = S.accept();
}
catch(IOException e)
{
System.out.println("IOError");
}
}
Firstly I wrote the code without try catch and I got an unreported exception java.io.IOException; must be caught or declared to be thrown Error but Netbeans didn't suggest that I add a try-catch block . Now I added the try-catch block manually but It still shows an error and suggests that I must add another try-catch block !

You're trying to add a try block at the top level of the class - you can't do that. Try blocks have to be in methods or initializer blocks.
If you really want to create the server socket on construction, put the code in a constructor:
public class Server {
private ServerSocket serverSocket;
private Socket firstConnection;
public Server {
try
{
serverSocket = new ServerSocket(3333);
firstConnection = serverSocket.accept();
}
catch(IOException e)
{
System.out.println("IOError");
}
}
}
I assume you'll have real exception handling (or rethrowing) rather than just catching the IOException and continuing, of course?

This is not valid Java. This code needs to be in a block, method, or constructor.

From the screenshot of your IDE, the error "must be caught or declared to be thrown" is not the only error you have.
When you have syntax that is this far off, the compiler will likely report several errors, some of which are side-effects of other errors - like not enclosing this code in a method (I'm sure the red X next to the catch block is reporting a similar error).

Related

Java mp3 file errors

I am new to programming and trying to insert the mp3 file on Mac, but I have errors with these codes. I have been looking for solutions for a long time but I was not able to find the right answers. I would like to know what I did wrong.
import javazoom.jl.player.Player;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class Music {
public static void main(String [] args) {
String filename = "src_music_typing.mp3";
MusicPlayer music = new MusicPlayer(filename);
music.play();
}
}
class MusicPlayer {
private final String mp3File;
private Player jlPlayer;
public MusicPlayer(String mp3File) {
this.mp3File = mp3File;
}
public void play() {
try {
FileInputStream fis = new FileInputStream(mp3File);
BufferedInputStream bis = new BufferedInputStream(fis);
jlPlayer = new Player(bis);
} catch (Exception e) {
System.out.println("problem file is " + mp3File);
System.out.println(e.getMessage());
}
new Thread() {
public void run() {
try {
jlPlayer.play();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}.start();
}
public void close() {
if(jlPlayer != null) jlPlayer.close();
}
}
Problem:
problem file is src_music_typing.mp3
src_music_typing.mp3 (No such file or directory)
Cannot invoke "javazoom.jl.player.Player.play()" because "this.this$0.jlPlayer" is null
The error is telling you simply that src_music_typing.mp3 does not exist; evidently you aren't running this in the directory you think you're running it in. Trivial solution: Make that path string (String filename = "src_...") an absolute path instead.
NB: It's a cavalcade of problems, here. Your code is bad and it leads to inefficient error messages. Inefficient enough to confuse you, for example.
You should never catch an exception just to log it and then blindly continue; I know a ton of code snippets do this, but that part of them is just bad. You don't want to do that - dealing with an error by blindly continuing on is, obviously, a really silly thing to do!
The right way to deal with exceptions that you don't explicitly know how to handle is instead to just throw them on. your play method should be declared as throws IOException, as this is inherent to your API design, this is fine (it's inherent because your music player class as a property that represents a file name, and anything file related is expected to throw IOExceptions, hence, fine - not leaking an abstraction).
Then the whole try/catch bit can just go away, yay! Your code is better and shorter and easier to understand, win win win!
Because you didn't do that, and you just run blindly on, you get a second error that is complaining about attempting to invoke play() on a null pointer. This error is meaningless, in that it's merely a symptom, not the cause. The cause is the first error message. This is one of a few key reasons why 'keep blindly going' is a really bad idea - it means you get a ton of meaningless, confusing errors after the actual problem, resulting in a ton of error output, most of which is just hiding the actual problem.
If you can't throw them on, a distant second best solution is to put this in your catch blocks: throw new RuntimeException("uncaught", e);. This preserves all error information (type, message, stack trace, causal chain - all of it), and still ensures code does not blindly continue when your method is an unknown (to you) state. If you have an IDE that inserts catch blocks for you, update its template.
NB: main can and usually should be declared as static void main(String[] args) throws Exception {.

java.lang.ClassCastException exception using ObjectInputStream, when sending a class as an object

https://github.com/IshayKom/RCProject
Classes As Shown in the eclipse package manager
(I don't really deal with github so I don't know how to upload classes correctly)
I got an error running my project.
I use VMWare to work on my project but I don't think that this specific error requires the use of multiple PCs or VMs.
It basically should receive ClientInformation from the InitiHandler class and start the process of matching two clients together. (Security isn't required in this project at the moment)
The steps to recreate this issue as follows: Enabling the "server" with the required information. After that go on "controlled client" mode, write the required information, and attempt to send info to the server.
I tried searching for a solution and looking at what mistake I did this time but I just can't get my mind into it. If anyone can spot my mistake it'll super helpful.
The following is the class which the error happened in:
package Server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerInitializer extends Thread {
private int port;
private ClientInformation[] ci = null;
private ClientInformation c = null;
private boolean run = true;
ServerSocket serversocket;
ObjectInputStream ois;
Socket client;
public ServerInitializer(int port, int clientlimit) {
this.port = port;
ci = new ClientInformation[clientlimit];
start();
}
#Override
public void run() {
try
{
serversocket = new ServerSocket(port);
while(run)
{
client = serversocket.accept();
System.out.println("New Client Has Been Connected, ip:" + client.getInetAddress().getHostAddress());
ois = new ObjectInputStream(client.getInputStream());
c = (ClientInformation) ois.readObject();
new ServerThread(ci,c, client, run);
}
serversocket.close();
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public void terminate()
{
this.run = false;
}
public boolean getrun()
{
return run;
}
}
The error itself:
"Exception in thread "Thread-0" java.lang.ClassCastException: class Startup.ClientInformation cannot be cast to class Server.ClientInformation (Startup.ClientInformation and Server.ClientInformation are in unnamed module of loader 'app')
at Server.ServerInitializer.run(ServerInitializer.java:35)"
If it's too much of a pain to see my mistake based on what I currently wrote let me know what to do to make it easier for you to spot it.
Another Question: How can I use the terminate function to basically disable any while loops that are happening in other classes/threads? or what I wrote is good enough? I couldn't test this because of my error. (This can apply to the server itself in my project or the client-side)
You have a class named ClientConfiguration, which has package Server; on the top. You have a completely different, totally unrelated class which by pure coincidence is also named ClientConfiguration, but has package Startup; at the top, which is why I say it is unrelated. Because that's what that means. You are then sending an instance of one of these, and upon receiving it, you assume it is the other. It isn't, hence, CCEx.
If you intended to have 2 different classes with the same name, stop confusing them; if this sounds difficult (I think it'd have some issues with this, too!), then rename one.
If you never intended to have 2 separate classes, then fix that problem. Possibly you already did and simply replaced the package statement (and moved the source file to another folder) for the only ClientConfiguration you ever had, but then one of the two (client or server) is running old code.

java.lang.NullPointerException PrintWriter

I am getting a NullPointerException when I run my code. I have narrowed down the problem to line 38: when it is commented out the program doesn't give any errors. I just have "test" here for now.
out.println("test")
The run method is immediately started with the following two lines in another class
Client test = new Client();
test.start();
And when a button is pressed the following code is executed which runs the sendToServer method
Client test = new Client();
test.sendToServer(cipherText)
Below is the full code for my Client class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client extends Thread{
String line = "";
String cipherText = "";
BufferedReader in;
PrintWriter out;
public void run(){
String serverAddress = "00.000.000.000";
try{
Socket socket = new Socket(serverAddress, 8888);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException e){
e.printStackTrace();
}
while (true) {
try{
line = in.readLine();
}
catch(IOException e){
e.printStackTrace();
}
System.out.println(line);
}
}
public void sendToServer(String in) {
out.println("test");
}
}
Thanks for looking, I am still learning java so excuse any obvious mistakes.
You have in the beggining of the class:
PrintWriter out;
if you don't call run() [is where you initialize it] before sendToServer(), "out" would never be initialized and will be null.
That is because you have used PrintWriter out; as your class member but you have not initialized it. By default, all un-initialized member objects are initialized with null. If sendToServer() is called first, out will be null and you will get NullPointerException.
EDIT
Problem is that you are trying to invoke run() and sendToServer() methods on two separate instances of Client.
Client test = new Client(); // First instance
test.start(); // which calls run() and then initializes out variable.
Then a second instance is created from:
Client test = new Client(); // Second instance
test.sendToServer(cipherText); // since out is not initialized for this instance, you are getting NPE
I suppose you are using Client object in a multi-threaded environment, in that case I would suggest you to make sure that both threads are using same instance of Client object. Also if Client instance is being shared, you might want to make access to out variable synchronized and also make sure that Client's run method is executed first before button is pressed (which in turn calls sendToServer()).
Your function assumes out Printwriter will be initialized, but if there is an exception in the socket initialization, it will never by initialized. Two things I would do...
1. Initialize out to null at the top of the run method.
2. protect your sendToServer code...
public void sendToServer(String in) throws NullPointerException
{
if (out == null)
{
throw new NullPointerException("Out is null.");
}
out.println("test");
}

NullPointerException from PrintWriter class and File creation

I've been working on a small bit of code and though the rest of the code works, there is an error with the logging system that I've written.
When the method log(String) is called, it throws a NullPointerException.
I thought this might be because the file might not be being created, but I'm not sure what I've done wrong and as far as I can tell the file should be being created (It's not) and even if I create the file and put it into the correct position, the exception is still thrown.
I've been tinkering around with it a bit, so some of it doesn't make sense, it's probably because it was while I was debugging.
Here's the code:
package UI;
import java.io.File;
import java.io.PrintWriter;
public class InputLogger {
//Necessary for interceptor pattern
private static PrintWriter output;
//For testing remove later
private static File logFile;
public InputLogger() {
initiate("log.txt");
}
public InputLogger(String anotherFile) {
initiate(anotherFile);
}
public void initiate(String filename) {
try {
/*File */logFile = new File(filename);
if(!logFile.exists()) {
if(!logFile.createNewFile())
System.err.println("Error creating log file. Please verify that files can be created.");
}
output = new PrintWriter(logFile);
} catch (Exception e) {
System.err.println("Error accessing log file. Please verify that files can be created.");
}
}
public static void log(String action) {
try {
output.println(action);
} catch (Exception e) {
e.printStackTrace(System.out);
System.err.println("Error printing to log file. Please verify that file exists or can be created.");
}
}
public void close() {
output.close();
}
}
I think it might have something to do with the fact that I call it as a static method, but I've been looking around and I can't seem to find an explanation elsewhere.
Edit:
I forgot to actually create an InputLogger object. Thanks guys.
Most likely you forgot to create an InputLogger object. Do this:
InputLogger logger = new InputLogger();
InputLogger.log( "hoooey" );
logger.close();
Not calling close may lose a line or two.
Mixing static with a constructor and proper methods is dangerous, and an antipattern. You might remain with static, with a lazy initialization which gives your program the chance to set the file name. Or, better, avoid the statics and do all in proper methods.
In the method initiate you initialize the output, but in your static method log it's not guaranteed to have been initialized before calling since.
To be safe you should always initialize the required static variables either in the static method or as a field declaration.
In this case in your initiate it is possible to throw an exception prior to the line output = new PrintWriter(logFile) which means output is null

Java - Can final variables be initialized in static initialization block?

Based on my understanding of the Java language, static variables can be initialized in static initialization block.
However, when I try to implement this in practice (static variables that are final too), I get the error shown in the screenshot below:
Yes of course: static final variables can be initialized in a static block but.... you have implicit GOTOs in that example (try/catch is essentially a 'GOTO catch if something bad happens').
If an exception is thrown your final variables will not be initialized.
Note that the use of static constructs goes against Object-Oriented dogma. It may complicate your testing and make debugging more difficult.
You can do this but you need to exit the static block by throwing an exception - you can rethrow the exception that was caught or a new one. Generally this exception must be a RuntimeException. You really should not catch a generic Exception but more specific exception(s) that might be thrown from within your try block. Finally, if a static initializer throws an exception then it will render the class unusable during that specific run because the JVM will only attempt to initialize your class once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError.
So, to work, your initializer should read something like this:
static {
try {
...
} catch (Exception e) {
e.PrintStackTrace();
throw new InitializationFailedException("Could not init class.", e);
}
}
Assuming that InitializationFailedException is a custom RuntimeException, but you could use an existing one.
public class MyClass
{
private static final SomeClass myVar;
static
{
Object obj = null; // You could use SomeClass, but I like Object so you can reuse it
try
{
obj = new SomeClass(...);
}
catch(WhateverException err)
{
// Possibly nested try-catches here if the first exception is recoverable...
// Print an error, log the error, do something with the error
throw new ExceptionInInitializerError(err);
}
finally
{
myVar = (SomeClass) obj;
}
}
}
Assuming no where upstream is in a position to catch either an ExceptionInInitializationError or a general Exception then the program should not ever try to use myVar. If however those are caught and the program doesn't end, then you need to code to watch for and handle myVar being null (or be happy with NullPointerExceptions coming out all over).
I'm not sure there is a good way to handle this.
Can you put the declaration in the finally block?
try {
//load file
} catch(IOException e) {
// horay
} finally {
HOST=config.get......
}

Categories