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 9 years ago.
Improve this question
Code:
package exceptiona;
import java.io.IOException
public class ExceptionTest {
#SuppressWarnings("empty-statement")
public static void main (String[] args)
{
// call exceptionA
try{
throw new ExceptionA();
} catch (Exception e){
e.printStackTrace(};
System.out.println ("threw Exception A")
// call exceptionB
try{
throw new ExceptionB();
} catch (Exception e) {
e.printStackTrace(};
System.out.println ("threw Exception B")
// throw a NullPointerException
try{
throw new NullPointerException
} catch (NullPointerException){
nu
}
// throw IOException
try{
throw new IOException();
} catch (IOException io){
io.printStackTrace();
}
}
}
You have several syntax errors:
// throw a NullPointerException
try{
throw new NullPointerException();
} catch (NullPointerException npe){
npe.printStackTrace();
}
You should definitely learn java syntax in order to start coding.
Refer here for tutorials to get started
in the second catch, you have a syntax error:
change
e.printStackTrace(};
to
e.printStackTrace();
Generally speaking, you should avoid catching NullPointerException as they are runtime and show a wrong code logic.
What you should do is make sure you don't give null arguments to methods that should not be null.
public class ExceptionTest {
#SuppressWarnings("empty-statement")
public static void main(String[] args) {
// call exceptionA
try {
throw new ExceptionA();
} catch (Exception e) {
e.printStackTrace();
System.out.println("threw Exception A");
// call exceptionB
try {
throw new ExceptionB();
} catch (Exception e1) {
e1.printStackTrace();
System.out.println("threw Exception B");
// throw a NullPointerException
try {
throw new NullPointerException();
} catch (NullPointerException nu) {
}
// throw IOException
try {
throw new IOException();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
Your syntax is slightly off use this one:
try{
throw new ExceptionA();
} catch (Exception e){
e.printStackTrace();
System.out.println ("threw Exception A");
}
// call exceptionB
try{
throw new ExceptionB();
} catch (Exception e) {
e.printStackTrace();
System.out.println ("threw Exception B");
}
After this you use a word called: "nu"?
try{
throw new NullPointerException(); //missing ();
} catch (NullPointerException np){
//nu ?
System.out.println("threw NullPointerException");
}
Related
For my final in Java we have a "exceptions" part on the test with try, catch, and finally calls. When I try to put the example code into Eclipse I get errors in the catch and throw new areas. All of the errors say "Can not be resolved to type".
How do I fix this so I can learn/review what the code is supposed to be doing?
Q4 Class
public static void main(String [] args)
{
Q4Exception q1 = new Q4Exception();
try{
q1.sampleMethod();
try{
q1.sampleMethod();
}
//This catch does not throw an error
catch(RuntimeException es)
{
System.out.println("A");
}
//This catch below throws the error of cannot be resolved to a type
catch(IOException es)
{
System.out.println("B");
}
//This catch does not throw an error
catch(Exception e)
{
System.out.println("C");
}
finally{
System.out.println("D");
}
}catch(Exception e)
{
System.out.println("E");
}
finally{
System.out.println("F");
}
}
Q4Exception Class
public void sampleMethod() throws Exception
{
try{
throw new IOException("H");
}
catch(IOException err)
{
System.out.println("I");
throw new RuntimeException("J");
}
catch(Exception e)
{
System.out.println(e.toString());
System.out.println("K");
throw new Exception(“L");
}
catch(Throwable t)
{
System.out.println("M");
}
finally{
System.out.println("N");
}
}
I think it's worth mentioning that in Eclipse, Ctrl+Shif+O does the job of resolving the imports for you.
Oh, guess I could answer my own question here.
Didn't know I had to import the IOException from java.io!
Easy to just use
import java.io.*
for the imports
I discovered I was using an old version of JWT , the issue is gone after using the a newer version of JWT dependency .
I need to handle Exceptions which are raised by Catch block code in Java
Example, to "handle" an Exception:
try
{
// try do something
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e.getMessage());
//Do some more
}
More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
However if you want another catch in your try catch, you can do the following:
try
{
//Do something
}
catch (IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
try
{
// Try something else
}
catch ( Exception e1 )
{
System.out.println("Caught Another exception: " + e1.getMessage());
}
}
Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:
try {
// do something here
}
catch(IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
foo();
}
private void foo()
{
try {
// do something here (when we have the IO exception)
}
catch(Exception e)
{
System.out.println("Caught another exception: " + e.getMessage());
}
}
Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.
Example :
public int classicMethodInCaseOfException(int exampleParam) {
try {
// TODO
}
catch(Exception e)
{
methodInCaseOfException();
}
}
public int methodInCaseOfException()
{
try {
// TODO
}
catch(Exception e)
{
//TODO
}
}
Do as you would do in an usual try/catch situation :
try{
throw new Exception();
}catch(Exception e1){
try{
throw new Exception();
}catch(Exception e2){
//do something
}
}
You can add new try catch block in your main catch block.
try
{
int b=10/0;
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException occurred");
try
{
int c=20/0;
}catch(ArithmeticException e1)
{
System.out.println("Another ArithmeticException occurred");
}
}
I think the most clean way is to create method which is catching the exceptions occurs in its body. However it can be very dependent to the situation and type of code you are dealing with.
One example of what you are asking about is closing a Stream which is opened in a try-catch-finally block. For example:
package a;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
//TODO: Log the exception and handle it,
// for example show a message to the user
} finally {
//out.close(); //Second level exception is
// occurring in closing the
// Stream. Move it to a new method:
closeOutPutStreamResource(out);
}
}
private static void closeOutPutStreamResource(OutputStream out){
try {
out.close();
} catch (IOException e) {
// TODO: log the exception and ignore
// if it's not important
// OR
// Throw an instance of RuntimeException
// or one of it's subclasses
// which doesn't make you to catch it
// using a try-catch block (unchecked)
throw new CloseOutPutStreamException(e);
}
}
}
class CloseOutPutStreamException extends RuntimeException{
public CloseOutPutStreamException() {
super();
}
public CloseOutPutStreamException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CloseOutPutStreamException(String message, Throwable cause) {
super(message, cause);
}
public CloseOutPutStreamException(String message) {
super(message);
}
public CloseOutPutStreamException(Throwable cause) {
super(cause);
}
}
Here I illustrated a situation which the second level exception is occurring in the finally block, but the same can apply for the exceptions occur in the catch block.
In my point of view writing methods such as closeOutPutStreamResource can be useful because they are packaging a boiler plate code for handling very common exceptions and they are making your codes more elegant.
Also it would be your choice to catch and log the exception in closeOutPutStreamResource or to throw it to other layers of your program. But it would be more elegant to wrap this unimportant checked exceptions into RuntimeException without a need for catching.
Hope this would be helpful.
You can use try catch block any where in methods or in block, so you can write try catch in catch block as well.
try {
// master try
}catch(Exception e){
// master catch
try {
// child try in master catch
}catch(Exception e1){
// child catch in master catch
}
}//master catch
It's not necessary to have a nested try-catch block when catch block throws Exception as all answers here suggest. You can enclose the caller method with try-catch to handle that Exception.
Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}
In the example below, you can see that the IOException (named FOURTH) exception cannot be caught using the outer catch clause. Why is that?
I know exceptions can be caught if its thrown in a nested try block, using outer catch.
If you change the b static variable value to false then you can see this.
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
import java.io.*;
public class Exceptions {
static boolean b = true;
public static void main(String[] args){
try {
exceptions(b);
} catch (Exception e) {
System.out.println(e + " is handled by main().");
}
}
static void exceptions(boolean b) throws Exception{
try{
if(b) throw new FileNotFoundException("FIRST");
try{
throw new IOException("SECOND");
}
catch(FileNotFoundException e){
System.out.println("This will never been printed out.");
}
}
catch(FileNotFoundException e){
System.out.println(e + " is handled by exceptions().");
try{
throw new FileNotFoundException("THIRD");
}
catch(FileNotFoundException fe){
System.out.println(fe + " is handled by exceptions() - nested.");
}
try{
throw new IOException("FOURTH");
}
finally{}
}
catch(Exception e){
System.out.println(e + " is handled by exceptions().");
}
}
}
The output if b = true :
java.io.FileNotFoundException: FIRST is handled by exceptions(). java.io.FileNotFoundException: THIRD is handled by exceptions() - nested. java.io.IOException: FOURTH is handled by main().
The output if b = false:
java.io.IOException: SECOND is handled by exceptions().
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
You can. The problem is that your last catch(Exception e) is at the same level of nesting which is why it doesn't catch an exception thrown in a previous catch block.
Try nesting your try/catch blocks like this
static void exceptions(boolean b) {
try {
try {
if (b) throw new FileNotFoundException("FIRST");
try {
throw new IOException("SECOND");
} catch (FileNotFoundException e) {
System.out.println("This will never been printed out.");
}
} catch (FileNotFoundException e) {
System.out.println(e + " is handled by exceptions().");
try {
throw new FileNotFoundException("THIRD");
} catch (FileNotFoundException fe) {
System.out.println(fe + " is handled by exceptions() - nested.");
}
// will be caught by the nested try/catch at the end.
throw new IOException("FOURTH");
}
} catch (Exception e) {
System.out.println(e + " is handled by exceptions().");
}
}
Your structure is some thing like this
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
Here catch1 and catch2 are at same level, and the exception thrown from catch1 will not reach catch2.
Hence Your IOE will be thrown back to the caller . If you want to handle the exception with in the method, then follow some thing below
try{
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
}
catch(Exce 3) {
// your IO will be caught here
}
I got a method that throw an exception if I try to insert an existing object in DB.
public void addInDB() throws Exception {
if (isInBase()){
throw new Exception ("[ReqFamily->addInDB] requirment already in base");
}
int idParent = m_parent.getIdBdd();
idBdd = pSQLRequirement.add(name, description, 0, idParent,
ReqPlugin.getProjectRef().getIdBdd(), 100);
}
So when the exception is thrown I wanna catch it and display an error messsage in my managed bean.
PS: In my managed bean I just call the method :
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
ex.printStackTrace();
}
}
Its bad practice to catch or throw Exception. If any code you use throws a checked exception then just catch that specific exception, and try to minimize the size of your try-catch blocks.
class MyException extends Exception {
...
public void addInDB() throws MyException {
if (isInBase()){
throw new MyException ("[ReqFamily->addInDB] requirment already in base");
}
...
void addReq(Requirement req){
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
try {
req.addInDB();
} catch (MyException ex){
ex.printStackTrace();
}
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
}
Try this:
try {
req.addInDB();//here i want to catch it
} catch (Exception ex){
ex.printStackTrace();
}
You can try this:
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
If you wanna capture all of stacktrace to be show in display, you can use this:
catch (Exception ex) {
String
ls_exception = "";
for (StackTraceElement lo_stack : ex.getStackTrace()) {
ls_exception += "\t"+lo_stack.toString()+"\r\n";
}
JOptionPane.showMessageDialog(null, ls_exception);
}