I want to catch an exception, print the place the exception occured and continue running the loop. I have this example code:
public class justcheckin {
static String[] l = {"a","a","b","a","a"};
public class notAexception extends Exception{
private static final long serialVersionUID = 1L;
notAexception (){
super();
}
notAexception(String message){
super(message);
}
}
private void loop () throws notAexception {
notAexception b = new notAexception("not an a");
for (int i = 0; i< l.length; i++){
if (! l[i].equals("a")){
throw b;
}
}
}
public static void main (String[] args) throws notAexception{
justcheckin a = new justcheckin();
a.loop();
}
}
I want to write a warning message, say "index 2 is not a", and continue running the loop.
How can I do it?
Thanks!
I think in your code there is no need to have try catch throw etc.
But still in your same code if you want to perform this,
public class justcheckin {
static String[] l = {"a","a","b","a","a"};
public class notAexception extends Exception{
private static final long serialVersionUID = 1L;
notAexception (){
super();
}
notAexception(String message){
super(message);
}
}
private void loop () throws notAexception {
notAexception b = new notAexception("not an a");
for (int i = 0; i< l.length; i++){
try{
if (! l[i].equals("a")){
throw b;
}
}catch(notAexception ne){
System.out.println("index "+i+" is not a");//index 2 is not a
}
}
}
public static void main (String[] args) throws notAexception{
justcheckin a = new justcheckin();
a.loop();
}
}
Related
public class Test {
public static void main(String[] args) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine().trim());
Object o;
Method[] methods = Inner.class.getEnclosingClass().getMethods();
for(int i=0;i<methods.length;i++) {
System.out.println(methods[i].invoke(new Solution(),8));
}
// Call powerof2 method here
} catch (Exception e) {
e.printStackTrace();
}
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
Is it possible to call powerof2() method ?
I am getting java.lang.IllegalArgumentException: argument type mismatch for invoke
Yes, things declared in the same top-level class can always access each other:
public class Test {
public static void main(String[] args) throws Exception {
Inner i = new Inner(); // Create an instance of Inner
Inner.Private p = i.new Private(); // Create an instance of Private through
// the instance of Inner, this is needed since
// Private is not a static class.
System.out.println(p.powerof2(2)); // Call the method
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
See Ideone
Reflection version:
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException {
Class<?> privateCls = Inner.class.getDeclaredClasses()[0];
Method powerMethod = privateCls.getDeclaredMethod("powerof2", int.class);
powerMethod.setAccessible(true);
Constructor<?> constructor = privateCls.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object instance = constructor.newInstance(new Inner());
System.out.println(powerMethod.invoke(instance, 2));
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
I've received a task about java.util.concurrent package of java. I've made it almost totally, but there is some bug or mistake. When the queue is empty and operator waits for 5 seconds method poll should retrieve null and pass it to the operator and operator goes home. But it doesn't happen. It retrieves null but doesn't pass it to the operator. Sorry for my English.)
public class Client extends Thread {
public CountDownLatch latch=new CountDownLatch(1);
private boolean waiting;
private final Random random=new Random();
public boolean isWaiting() {
return waiting;
}
public void setWaiting(boolean isWaiting) {
this.waiting = isWaiting;
}
private static final Logger LOGGER;
static {
LOGGER = Logger.getLogger(Client.class);
new DOMConfigurator().doConfigure("log4j.xml",
LogManager.getLoggerRepository());
LOGGER.setLevel(Level.INFO);
}
private int limitTime=new Random().nextInt(5000);
public void run(){
ClientQueue.enqueueClient(this);
while(waiting){
if (random.nextBoolean()){
try {
latch.await(5, TimeUnit.SECONDS);
if (!waiting) return;
ClientQueue.removeFromQueue(this);
reportTiredToWait();
sleep(random.nextInt(1000)+500);
ClientQueue.enqueueClient(this);
reportDecidedToCallAgain();
} catch (InterruptedException e) {
LOGGER.info("Exception");
}
}
}
}
public Client(String name) {
super(name);
this.waiting=true;
}
private void reportTiredToWait(){
LOGGER.info("Client "+getName()+" was tired to wait and decided to hang up");
}
private void reportDecidedToCallAgain(){
LOGGER.info("Client "+getName()+" decided to call again");
}
#Override
public String toString() {
return "Client "+getName();
}
}
public class ClientQueue {
private static final Logger LOGGER;
static {
LOGGER = Logger.getLogger(ClientQueue.class);
new DOMConfigurator().doConfigure("log4j.xml",
LogManager.getLoggerRepository());
LOGGER.setLevel(Level.INFO);
}
private static ClientQueue instance;
private BlockingQueue<Client> queue;
public static void printQueue(){
System.out.println("LIST OF CLIENTS:");
for (Client client :ClientQueue.getInstance().queue){
System.out.println("CLIENT "+client.getName());
}
System.out.println("END OF LIST OF CLIENTS:");
}
private static ClientQueue getInstance()
{
if ( instance == null )
{
instance = new ClientQueue();
}
return instance;
}
private ClientQueue()
{
this.queue = new LinkedBlockingQueue<Client>();
}
public static void enqueueClient(Client client){
getInstance().queue.add(client);
reportClientEnqueued(client.getName());
}
public static void removeFromQueue(Client client){
ClientQueue.getInstance().queue.remove(client);
reportClientDeletedFromQueue(client.getName());
}
public static Client pollFirst(long time, TimeUnit timeUnit) throws InterruptedException{
Client client=null;
client = getInstance().queue.poll(time, timeUnit);
if (client!=null){
reportClientRetrievedFromQueue(client.getName());
}
return client;
}
private static void reportClientEnqueued(String name){
LOGGER.info("Client "+name+" was put on the waiting list");
}
private static void reportClientDeletedFromQueue(String name){
LOGGER.info("Client " +name+" was deleted from waiting list");
}
private static void reportClientRetrievedFromQueue(String name){
LOGGER.info("Client " +name+" was retrieved from waiting list");
}
}
public class Operator extends Thread{
private static final Logger LOGGER;
static {
LOGGER = Logger.getLogger(Operator.class);
new DOMConfigurator().doConfigure("log4j.xml",
LogManager.getLoggerRepository());
LOGGER.setLevel(Level.INFO);
}
private boolean running;
public Operator(String name){
super(name);
running= true;
}
#Override
public void run() {
while (running){
Client client=null;
try {
client = ClientQueue.pollFirst(5, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (client!=null){
String clientName=client.getName();
reportOperatorReceivedCall(clientName);
try {
client.setWaiting(false);
client.latch.countDown();
sleep(10000);
reportOperatorFinishedConversation(clientName);
} catch (InterruptedException e) {
LOGGER.error(e);
}
} else{
reportOperatorFinishedHisWork();
running=false;
}
}
}
private void reportOperatorReceivedCall(String name){
LOGGER.info("Operator "+getName()+" received call from Client "+name);
}
private void reportOperatorFinishedConversation(String name){
LOGGER.info("Operator "+getName()+" finished conversation with Client "+name);
}
private void reportOperatorFinishedHisWork(){
LOGGER.info("Operator "+getName()+" finished his work for today, he is too tired and decided to go home.");
}
}
public class Main {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
LinkedList<Client> clientList = new LinkedList<Client>();
clientList.add(new Client("Vasya"));
clientList.add(new Client("Tanya"));
clientList.add(new Client("Petya"));
clientList.add(new Client("Kolya"));
clientList.add(new Client("Elena"));
clientList.add(new Client("Anna"));
for(int i = 0; i < clientList.size(); i++) {
executor.schedule(clientList.get(i), i, TimeUnit.SECONDS);
}
LinkedList<Operator> operatorList = new LinkedList<Operator>();
operatorList.add(new Operator("Bob"));
operatorList.add(new Operator("Sandra"));
operatorList.add(new Operator("John"));
for(int i = 0; i < operatorList.size(); i++) {
executor.schedule(operatorList.get(i), 500, TimeUnit.MILLISECONDS);
}
}
}
You have an extra semicolon in ClientQueue.pollFirst. Here it is corrected:
public static Client pollFirst(long time, TimeUnit timeUnit) throws InterruptedException{
Client client=null;
client = getInstance().queue.poll(time, timeUnit);
if (client!=null) { // removed semicolon from this line
reportClientRetrievedFromQueue(client.getName());
}
return client;
}
I am facing problems when using try/catch
I created an exception class called EmptyQueueException that extends from Exception
Unfortunately, Eclipse throws me an error :" Catched expected instead"
public class Testclass {
public static void main(String[] args) {
ArrayQueue arrayy = new ArrayQueue();
try{
arrayy.dequeue();
}
catch(EmptyQueueException s){
// what to do here ?
}
} // end main
} // end testclass
Here is my Exception class:
public class EmptyQueueException extends Exception {
// automatically done by eclipse, what for?
private static final long serialVersionUID = 1L;
public EmptyQueueException() {
}
public EmptyQueueException(String s){
super("Queue is empty");
}
}
This is my dequeue method:
public int dequeue() throws EmptyQueueException {
if (empty()){
throw new EmptyQueueException();
}
int retour = head();
head = ++head % array.length;
return retour;
}
I have this Exception:
public class ErrorException extends Exception
{
private static final long serialVersionUID = 1L;
private String errorMessage = "";
private int errorCode = 0;
private String errorLevel = "";
private Window errorSource = null;
public String getErrorMessage()
{
return errorMessage;
}
public int getErrorCode()
{
return errorCode;
}
public String getErrorLevel()
{
return errorLevel;
}
public Window getErrorSource()
{
return errorSource;
}
public ErrorException(String message, int code, int level, Window source)
{
super();
errorMessage = message;
errorCode = code;
switch (level)
{
case 0:
{
errorLevel = "benignError";
}
case 1:
{
errorLevel = "criticalError";
}
case 2:
{
errorLevel = "terminalError";
}
}
errorSource = source;
}
}
And I have this method:
public static Element check(final Document document) throws ErrorException
{
try
{
chapter.resetLatch();
final SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
new Thread()
{
#Override
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
answer.getPreviousElement().takeFocus();
question.removeAnswer(answer);
question.rewriteLetters();
Utils.update(chapter);
loop.exit();
}
});
}
}.start();
loop.enter();
chapter.getLatch().await();
}
catch (InterruptedException e)
{
throw new ErrorException("blankElementDialogError", 8, 1, Main.getGui().getMasterWindow());
}
return new Element();
}
And I use it in this constructor code:
public ConfirmCloseDialog(final Document document, final int postOperation)
{
final CustomJButton doSave = new CustomJButton(Main.getString("doSave"), false);
doSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
getConfirmCloseDialog().dispose();
new Thread()
{
#Override
public void run()
{
/*this method is the one above -->*/Element problem = BlankElementDialog.check(document);
if (problem == null)
{
new SaveChooser(document, postOperation);
}
else
{
new BlankElementDialog(problem);
}
}
}.start();
}
});
}
The code for the second part is not full, but there are no special constructs in the rest of the code (just some GUi objects being constructed and there is no try catch anywhere in the constructor).
However, Eclipse isn't forcing me to encapsulate the method call into try catch block, despite the fact that the method throws an Exception (ErorrException subclasses Exception).
And I know that Exception is checked exception, so it should force it, right?
Why?
What do I have to do so it would force it?
Even without any details Eclipse should notify, look at this:
Just restart the Eclipse should solve the issue.
public class TestClass {
public static void main(String[] args) {
method(2);//Notification here!
}
static void method(int a) throws myException {
}
}
class myException extends Exception {
}
Can i use the following code? It's not throwing any error at the Object but at obj.i. Is this a legal way of using an object? Also, how many ways can i create an object other than using the normal syntax obj s = new obj();
public class Test {
static int i;
static Test obj;
obj.i = 10; //am getting a compilation error here "Syntax error on token "i", VariableDeclaratorId expected after this token"
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}
You need to place a static block around the obj.i assignment statement for this to work:
public class Test {
static int i;
static Test obj;
static { obj.i = 10; }
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}
This is not, you didn't initialize. Furthermore you might not want to use static.
public static void main(String [] args) {
int i = 10;
Test obj = new Test();
obj.setI(i);
System.out.println("my objects I = "+ obj.getI());
}
now in your Test object
public class Test {
private int i;
public void setI(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
}