Try, catch and Exception handling [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Test class:
package learning;
import java.io.IOException;
import java.util.Scanner;
public class Test {
static Scanner user = new Scanner(System.in);
public static void main(String[] args) {
Test2 t = new Test2();
try {
t.run(0);
} catch (Exception e) {
try {
t.run(user.nextInt());
} catch (Exception ee) {
try {
t.run(user.nextInt());
} catch (Exception dd) {}
}
}
}
}
Test2 class:
package learning;
import java.io.IOException;
public class Test2 extends Test {
public int x = 0;
public void run(int a) throws Exception, IOException {
do {
if (a > 1)
System.out.println(a);
x = x + 1;
if (a < 1) {
System.out.println("you're wrong");
throw new Exception();
}
} while (x==0);
}
}
It will stop running if a > 0, but when I answer with a string it will also stop running. How do I get the program to ask again and if I enter 2 times a number below 1 it will also stop running how do I make it endless?

Easiest way to make anything endless is to throw a while(true) loop on it. Better programming practices may include properly disposing by doing while(started) and setting started to false.
In your case I am not sure what you intention is... so the following should work. Also get rid of that do while loop. To be honest this code can totally be written cleaner but you can just play around for now.
public class Test {
static Scanner user = new Scanner(System.in);
public static void main(String[] args) {
Test2 t = new Test2();
while(true) {
try {
t.run(user.nextInt());
Thread.Sleep(50);
} catch (Exception e) {
}
}
}

Related

NoSuchMethodException not caught [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to catch the NoSuchMethodException in the following code:
try {
method = currentClass.getMethod(arg1,arg2);
break;
}
catch (NoSuchMethodException e) {
System.out.println("hi");
}
It's not getting caught. I've tried catch (Throwable e) and catch (Exception e) and catch (NoSuchMethodError e) but none of them worked.
Even though When I run the code the console shows a NoSuchMethodException, but it's not getting caught.
You are using getMethod in a wrong way. You must pass the name of the method and an array of arguments to it. Given below is an example of the correct way:
class Main {
public static void main(String[] args) {
try {
Class[] arguments = new Class[1];
arguments[0] = String.class;
String.class.getMethod("concat", arguments);
} catch (NoSuchMethodException e) {
System.out.println("Error occured");
}
}
}
Check the signature of String#concat which takes an argument of type, String.
Another example:
class MyClass {
public void hello(String name) {
System.out.println("Hello " + name);
}
public int getSum(int x, int y) {
return x + y;
}
}
class Main {
public static void main(String[] args) {
try {
Class[] arguments = new Class[1];
arguments[0] = String.class;
MyClass.class.getMethod("hello", arguments);
System.out.println("This one passed.");
arguments = new Class[2];
arguments[0] = int.class;
arguments[1] = int.class;
MyClass.class.getMethod("getSum", arguments);
System.out.println("This one too.");
// The following one will fail
MyClass.class.getMethod("foo");
} catch (NoSuchMethodException e) {
System.out.println("Error occured");
}
}
}
Output:
This one passed.
This one too.
Error occured
Update:
This update is based on the following valuable comment from Holger:
getMethod is a varargs method. There is no need to deal with arrays manually. You can use String.class.getMethod("concat", String.class);,
MyClass.class.getMethod("hello", String.class);, and MyClass.class.getMethod("getSum", int.class, int.class);. In fact, your MyClass.class.getMethod("foo"); statement is already using that feature, as it doesn’t create the zero length Class[] array manually.
class MyClass {
public void hello(String name) {
System.out.println("Hello " + name);
}
public int getSum(int x, int y) {
return x + y;
}
}
class Main {
public static void main(String[] args) {
try {
MyClass.class.getMethod("hello", String.class);
System.out.println("This one passed.");
MyClass.class.getMethod("getSum", int.class, int.class);
System.out.println("This one too.");
// The following one will fail
MyClass.class.getMethod("foo");
} catch (NoSuchMethodException e) {
System.out.println("Error occured");
}
}
}
Java exception hierarchy looks like so:
Throwable
| |
Error Exception
|
RuntimeException
Errors are intended for signaling regarding problems in JVM internals and other abnormal conditions which usually cannot be handled by the program anyhow. So, in your code you are not catching them. Try to catch Throwable instead:
boolean result = false;
try{
result = Settings.canDrawOverlays(context);
}
catch(Throwable e){
Log.e("error","error");
}
Also it's a good idea to read this
There are two variants to this
NoSuchMethodError - which has base class as Error - and is used by compiler to detect absence of the method used or at runtime when you lets say upgrade or downgrade a particular dependent jar and the method is not defined in the class in the new jar included.
NoSuchMethodException - which has base class as Exception, this you usually get when using reflection and the method with 'name' you are trying to access is not defined in that class.
However, both should be caught if you have catch block with Throwable as Throwable is the base of both Error and Exception.
import java.lang.reflect.Method;
public class NoSuchMethodMethodTest
{
public static void checkIfMethodNotExist()
{
try
{
final NoSuchMethodMethodTest noSuchMethodMethodTest = new NoSuchMethodMethodTest();
Class clazz = noSuchMethodMethodTest.getClass();
final Method m = clazz.getMethod("demo", null);
}
catch (NoSuchMethodException e)
{
System.out.println("demo method not exist");
}
}
public static void checkIfMethodExist()
{
try
{
final NoSuchMethodMethodTest noSuchMethodMethodTest = new NoSuchMethodMethodTest();
Class clazz = noSuchMethodMethodTest.getClass();
final Method m = clazz.getMethod("main", String[].class);
}
catch (NoSuchMethodException e)
{
System.out.println("main method exist");
}
}
}

Where should I put the throws InterruptedException for the sleep function in java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've looked up where to put it and all I'm getting are mixed answers and the purpose of this is to create rudimentary for the alpha version of this game. Here is the code:
public class Intelijence {
public static void main(String[] args) {
System.out.println("OK, That looks perfect");
Thread.sleep(5000);
System.out.println("Huh, What's that");
}
}
I know that there is no throws InterruptedException. I'm just wondering where to put it.
You can declare it in the throws clause on the main method. If you are certain that the sleep will not be interrupted, this is the best option.
public class Intelijence {
public static void main(String[] args) throws InterruptedException {
System.out.println("OK, That looks perfect");
Thread.sleep(5000);
System.out.println("Huh, What's that");
}
}
You could also catch it if it requires handling.
public class Intelijence {
public static void main(String[] args){
System.out.println("OK, That looks perfect");
try{
Thread.sleep(5000);
} catch(InterruptedException e){
//handle exception
e.printStackTrace();
}
System.out.println("Huh, What's that");
}
}
Thread.sleep throws an InterruptedExcpetion - you need to either catch it, or declare a throws clause in the method the calls it - in this case, main:
public class Intelijence {
public static void main(String[] args) throws InterruptedException {
// Here ---------------------------^
System.out.println("OK, That looks perfect");
Thread.sleep(5000);
System.out.println("Huh, What's that");
}
}
You have two primary options
declare that main throws interrupted-exception
just put try { } catch () {} around the sleep statement, and enter a short error message stating something like "Should never get here"
Use something like this i.e. Adding throws keyword in the method signature itself which will pass the exception to the calling method:
public class Intelijence {
public static void main(String[] args) throws InterruptedException {
System.out.println("OK, That looks perfect");
Thread.sleep(5000);
System.out.println("Huh, What's that");
}
}
Or
Use something like i.e. Try-Catch blocks to handle that exception then and there only:
public class Intelijence {
public static void main(String[] args){
System.out.println("OK, That looks perfect");
try {Thread.sleep(5000);}
catch (InterruptedException e){ e.printStackTrace();}
System.out.println("Huh, What's that");
}
}
I think this will help you.

Is there a nicer solution for (not) continuing after try catch in a method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Right now my solution looks like this:
public void method() {
int number;
boolean continue = true;
try {
number = parseInt(this.something);
} catch (NumberFormatException e) {
//some code
continue = false;
}
if (continue) {
//more code
}
}
Is there something prettier out there?
Is there a nicer solution for (not) continuing after try catch in a method?
The intended way is to write the code that should be skipped inside the try block:
public void method() {
try {
int number;
number = parseInt(this.something);
//more code
} catch (NumberFormatException e) {
// log exception
// do things to recover from the error if possible
// maybe rethrow `e` or throw another exception
}
// avoid to write some code here, usually it is wrong.
}
Even though it is a void method, you can use return; which then will exit the method. Therefore a perfectly fine solution to your "problem" is to just use return and removing the if as follows:
public void method() {
int number;
try {
number = parseInt(this.something);
} catch (NumberFormatException e) {
//some code
return;
}
//more code
}
If the object is not setup properly (this.something was not set), it might be better to throw then catch in the calling code. If you just return, the caller might assume the method completed successfully. Otherwise the code provided by Aidin would work.
You can simply ignore the exception and log the exception for information purpose:
public void method() {
int number;
try {
number = parseInt(this.something);
} catch (Exception ignored) {
// here could be some System.out.println or a logging API
}
}
But if you have a return, just return null and evaluate your result whether is null or not.
public Integer method() {
try {
return parseInt(this.something);
} catch (Exception ignored) {
// here could be some System.out.println or a logging API
}
return null;
}
Integer number = method();
if (number != null) {....
You could use retun; break; or possibly System.exit()

Why sysout allways prints 1? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In below code, why sysout allways prints 1?
public class A implements ActionListener{
public static int X = 0;
private Timer timer;
public A(){
timer = new Timer(16 ,this);
timer.setInitialDelay(16);
timer.start();
}
public void actionPerformed(ActionEvent arg0) {
System.out.println(X);
}
public static void main(String args[]){
new A();
new B().start();
}
}
class B extends Thread{
public void run(){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
A.X++;
}
}
I expect something like this output:
1
2
3
...
Note that I dont want to use another approach.
It is because the run method of threads is called only once. If you want to see your expected result try this:
class B extends Thread{
public void run(){
try {
while(true){ //add here some condition when you want to stop the loop
A.X++;
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Java Jlayer Mp3 Player - how to repeat and stop song [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have problem with mp 3 player. I'm using jLayer.
This is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) {
new Thread (){
public void run(){
try
{
Player prehravac;
FileInputStream buff = new FileInputStream(Okno.filename);
prehravac = new Player(buff);
prehravac.play();
if (prehravac != null)
{
prehravac.play();
}
}
catch(Exception e)
{
}
}
}.start();
}
In my application I need to play song from the beginning to the end. So when song ends I need to start it again and when window closes I want to stop this song...
JLayer does not support continuous play, so you have to use a loop to repeatedly start a new player after the old one finished. For example:
try
{
do
{
FileInputStream buff = new FileInputStream(Okno.filename);
prehravac = new AdvancedPlayer(buff );
prehravac .play();
}while(loop);
}
catch(Exception ioe)
{
//TODO error handling
}
with loop being a boolean you can set true or false in a different method depending on if you want it to be played just once or repeatedly.
If you want to access the thread later you should at least declare it to a variable. Even better is writing a seperate class that extends thread. Doing so you can add method to the thread you can later call.
For your code it might look something like that:
import java.io.*;
import javazoom.jl.player.*;
public class MyAudioPlayer extends Thread {
private String fileLocation;
private boolean loop;
private Player prehravac;
public MyAudioPlayer(String fileLocation, boolean loop) {
this.fileLocation = fileLocation;
this.loop = loop;
}
public void run() {
try {
do {
FileInputStream buff = new FileInputStream(fileLocation);
prehravac = new Player(buff);
prehravac.play();
} while (loop);
} catch (Exception ioe) {
// TODO error handling
}
}
public void close(){
loop = false;
prehravac.close();
this.interrupt();
}
}
With this you can simply create the Thread when and wherever you want like this:
private MyAudioPlayer thePlayer;
[... some class code here...]
public void yourMethod(){
thePlayer = new MyAudioPlayer("path of the music file", true);
thePlayer.start();
}
and if you want to get rid of it at some point call thePlayer.close();
Note that thePlayer should be an instance variable so you can reuse it again. If you only declare it within a method it will disappear after the method is finished.
Hope this helps.

Categories