A question about sorts of using exception

  • Thread starter Thread starter transgalactic
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
7 replies · 3K views
transgalactic
Messages
1,386
Reaction score
0
i know only the try catch method
that says
for that king of excepion do this

but i saw some weird other implementation
like in the signature of the method "throws exception"
ok now what? it doesn't say what to do in a case of an exception
it just say "throws exception"
what other sorts of exception implementation are there??
 
Physics news on Phys.org
I'm having a hard time understanding your question.

You don't need (in most languages anyway) to catch a specific type of exception.

Code:
try { int a = 1 / 0; }
catch (DivisionByZeroException e) { Console.Out.WriteLine("Division by Zero"); }

vs

Code:
try { int a = 1 / 0; }
catch (Exception e) { Console.Out.WriteLine("Something bad happened"); }

(This is c#, your exact vocabulary may vary).

If you catch an unspecified exception, it is sort of up to you what you want to do about it. It depends on the situation. Sometimes you might want to just fail silently (if say your program is checking for updates of itself and can't connect to the server), sometimes you want to display the details of the exception to the user (for most errors) and leave "what to do next" to him or her, and sometimes you want to shut down completely.

k
 
i forgot to mention that this is java
 
can you answer this question for JAVA
 
In java, all exceptions inherit from the Exception class, so you can catch that one if you don't know what you are looking for.

Code:
try 
{ 
    .. 
}
catch (Exception e) 
{
    System.err.println("Error :" + e.getMessage());
}

k
 
Last edited:
ye but that's not the only sort
there is the case of a method throws exception

were is the catch stuff there
cause i saw implementation without any catch in this sort of implementation
 
Are you saying that you throw classes that don't derive from the Exception class? In that case you'd have to know what to catch since you wrote the code. But in general you should only throw Exceptions; you should add "extends Exception" to any class you're throwing. (N.B.: not to any class that throws exceptions, only classes that are themselves exceptions!)
 
In Java, when you're calling any methods that may throw a given exception, then your options are to use a try/catch to handle the exception or to mark your current method as able-to-throw that exception (using "throws").

This ensures that, even though you're choosing not to handle a given exception in your code, the code that is calling your method will handle that exception itself (or its caller, etc). You use "throws" to delegate the handling of the exception to the caller.