Catching or Methods Throwing Exceptions
Hi,
I'm just wondering whats the difference between catching an exception and a method throwing an exception?
I'm a bit confused on their purpose dealing with exceptions.
catching an exception
void p1()
try{
p2();
}catch(IOException ex){
}method throwing an exception
void p1() throws IOException
p2();
}
one more stuff i need to add is that:
When we declare a particular code within a try catch
statement it means that that particular code is very
much prone to an exception , i mean the programeer
knows that code will throw a exception and hence we
mention in try catch block.
But in other case when we suffixed that particular
method with throws clause it means the programmer is
not sure ,that code might throw an exception,hence we
put in throws clause.Not quite, the programmer always knows if a checked exception is being thrown, since the compiler requires it to be caught or having a throws clause. Unchecked (runtime) exceptions don't require a throws clause and the programmer must/can catch it if he wants to.
Similar Messages
-
Exceptions - documentation on which methods throw exceptions ?
Hi, does anyone know where I can find full documentation on iphone SDK methods
The iphone SDK documentation seems to be incomplete.
For instance, the discussion section of the SDK documentation for NSMutableArray addObject method doesn't mention anything about exceptions.
However, the method could throw an exception (and this is mentioned in http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMu tableArray_Class/Reference/Reference.html)
I'm assuming that alloc will not throw exceptions and that it will just return nil if no memory is available. However, I haven't found any documentation that states this.
Does anyone have a pointer to Apple documentation for methods (that includes information on any (and all) exceptions thrown by the method and also includes information on possible return values for the method) ?There is this
http://java.sun.com/products/jdbc/driverdevs.html
I am pretty sure that there is little in the meta data stuff that has to be supported. -
Exporting methods that throw exceptions?
Using 10g Preview, I have encountered the following situation:
I've written a custom method in my ViewRowImpl class that I intend to export as a client row method. It's a public void method that takes a single String parameter.
Originally, I declared that the method throws Exception. With the throws clause present, the View Object wizard does not display the method in the list of available methods to export to the client. Removing the throws clause causes the method to appear in the list.
There's nothing in the documentation that I can find to explain this apparent restriction. The closest thing I can find has to do with all types in the signature being Serializable. Nothing is mentioned about exceptions.
Can somebody explain why methods that declare thrown exceptions can't be exported to the client? Or does the type of exception declared need to be narrower, such as a JboException?I wondered the same thing. Take a look at this thread:
Why can't I throw exception from the Impl? -
Why Integer. valueOf(String,radix) throws exception
Can any one explains why this method throws exception
Integer a = Integer. valueOf(" 123 ", 2);
System.out.println(a);prady_jo wrote:
Can any one explains why this method throws exception
Integer a = Integer. valueOf(" 123 ", 2);
System.out.println(a);As already mentioned, in binary notation, only 1's and 0's are permitted. Besides that, I see you also have some white spaces in your string: this will throw an exception as well. -
How to throw exception in run() method of Runnable?
Hi, everyone:
I want to know how to throw exception in run() method of interface Runnable. Since there is no throwable exception declared in run() method of interface Runnable in Java API specification.
Thanks in advance,
GeorgeThanks, jfbriere.
I must add though that if your run() methodis
executed after a call to Thread.start(), then
it is not a good choice to throw anyRuntimeException
from the run() method.
The reason is that the thrown exception won't be
handled appropriately by a try-catch block.Why do you say that "the thrown exception won't be
handled appropriately by a try-catch block"? Can you
explain it in more detail?
regards,
George
Because the other thread runs concurrently with and independently of the parent thread, there's no way you can write a try/catch that will handle the new thread's exception: try {
myThread.start();
catch (TheExceptionYouWantToThrowFromRun exc) {
handle it
do the next thing This won't work because the parent thread just continues on after myThread.start(). Start() doesn't throw the exception--run() does. And our parent thread here has lost touch with the child thread--it just moves on to "do the next thing."
Now, you can do some exception handling with ThreadGroup and uncaughtException(), but make sure you understand why the above won't work, in case that was what you were planning to do. -
How to throw Exception in Thread.run() method
I want to throw exception in Thread.run() method. How can I do that ?
If I try to compile the Code given below, it does not allow me to compile :
public class ThreadTest {
public static void main(String[] args) {
ThreadTest.DyingThread t = new DyingThread();
t.start();
static class DyingThread extends Thread {
public void run() {
try {
//some code that may throw some exception here
} catch (Exception e) {
throw e;//Want to throw(pass) exception to caller
}(a) in JDK 1.4+, wrap your exception in RuntimeException:
catch (Exception e)
throw new RuntimeException(e);
[this exception will be caught by ThreadGroup.uncaughtException() of this thread's parent thread group]
In earlier JDKs, use your own wrapping unchecked exception class.
(b) if you know what you are doing, you can make any Java method throw any exception using Thread.stop(Throwable) regardless of what it declares in its "throws" declaration. -
Why jsp throw exception , but error page can' t catch it .
I use japanese Unix.
so must add follow
<%@ page contentType="text/html;charset=SJIS" %>
then error happen
Jim Clark wrote:
> I'm not sure what the problem is, but the following works for me in WL5.1
> SP3 on NT:
>
> <%@ page errorPage="testerror.jsp" %>
> <h1>hello</h1>
> <%
> String yes = "yes";
> if ( yes.equals("yes")) throw new IllegalStateException("yes");
> %>
>
> The page that shows is my testerror.jsp. Double check your page directive
> specifying your error page.
>
> --
> Jim Clark
> Idea Integration
> http://www.idea.com
>
> "yang" <[email protected]> wrote in message news:[email protected]...
> > I use error page , but jsp have exception . error page not catch it.
> >
> > throw follow exception only
> >
> > ? 6 19 19:01:03 JST 2000:<E> <ServletContext-General> Servlet failed
> > with Exception
> >
> > java.lang.IllegalStateException: Attempt to change ContentType after
> > calling getWriter() (cannot cha
> > nge charset from 'SJIS' to 'null')
> > at java.lang.Throwable.fillInStackTrace(Native Method)
> > at java.lang.Throwable.fillInStackTrace(Compiled Code)
> > at java.lang.Throwable.<init>(Compiled Code)
> > at java.lang.Exception.<init>(Compiled Code)
> > at java.lang.RuntimeException.<init>(Compiled Code)
> > at java.lang.IllegalStateException.<init>(Compiled Code)
> > at
> > weblogic.servlet.internal.ServletResponseImpl.setEncoding(Compiled Code)
> >
> > at
> > weblogic.servlet.internal.ServletResponseImpl.setContentType(Compiled
> > Code)
> > at
> > weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
> > at
> > weblogic.servlet.internal.RequestDispatcherImpl.forward(Compiled Code)
> > at weblogic.servlet.jsp.PageContextImpl.forward(Compiled Code)
> > at
> > jsp_servlet._aeonmarket._loan._W_95_AEL032._jspService(Compiled Code)
> > at weblogic.servlet.jsp.JspBase.service(Compiled Code)
> > at
> > weblogic.servlet.internal.ServletStubImpl.invokeServlet(Compiled Code)
> > at
> > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
> > Code)
> > at
> > weblogic.servlet.internal.ServletContextImpl.invokeServlet(Compiled
> > Code)
> > at
> > weblogic.servlet.internal.ServletContextManager.invokeServlet(Compiled
> > Code)
> > at weblogic.socket.MuxableSocketHTTP.invokeServlet(Compiled
> > Code)
> > at weblogic.socket.MuxableSocketHTTP.execute(Compiled Code)
> > at weblogic.kernel.ExecuteThread.run(Compiled Code)
> >
-
Throwing exceptions in an actionPerformed method
it tells me I can't do it
is there a way to get around this?
I'm reading a file inside the method so thats the exception in case it mattersIt's not in swing.. i'm making it on eclipse
public void actionPerformed(ActionEvent e) {
read();
//do some stuff
private void read() throws Exception{
BufferedReader reader = new BufferedReader(new FileReader(file));
//read some stuff
thats the lines that are causing me trouble, the only thing i've learned to do is throw exceptions in read() though I know there are better ways such as try{ and catching specific exception I don't know how to use them.
when I try to make actionPerformed throw Exceptions like I did to read() it says:
Exception Exception is not compatible with throws clause in ActionListener.actionPerformed(Action Event)
So... I don't know what to do and this is the final step in a program i've been making for a while now. -
PrintWriter methods throw NO exceptions!
Hi,
According to the PrintWriter javadoc:
"Methods in this class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError()."
I think this sounds strange in Java language, since it has the Exceptions mechanism...does any one know the reason why it is like this?
RegardsWith unchecked exception, it will still terminate my function mid-way!
Here is a concrete example:
public void method1() {
try {
... open database then read 1 entry ...
file.println("Entry is "+x);
method2();
... close the DB connection properly.
} catch(DBException ex) {
... deal with the DB failure accordingly
public void method2() {
try {
... open a webconnection then read 1 webpage ...
file.println("Webpage is" + y);
... now close the web connection
} catch(webException ex) {
... deal with the Web failure in a web-specific way
}If println throws exception (checked or unchecked), then I must wrap method1 AND method2
in yet another try/catch block. Otherwise, the function will die halfway, and my database or web connection
will be in a funky state.
By not throwing any exception (unless OutOfMemory or other dire situation),
I can write method1 and method2 without worrying about it.
And then at the end, I just check to see if all the writes succeeded or not. -
One method throw many exception
7. Create three new types of exceptions. Write a class with a method that throws all three. In main( ), call the method but only use a single catch clause that will catch all three types of exceptions.
Ok, I am learning java language from bruce eckel book. That is the exercise. I m having dificulties.
How can one method throw more than one exception?
class Satu extends Exception
Satu() { }
class Dua extends Exception
Dua() { }
class Tiga extends Exception
Tiga() { }
class ThisIsIt
public void f() throws Satu, Dua, Tiga
throw new Satu();
throw new Dua();
throw new Tiga();
public class Enam
public static void main( String[] args )
try
ThisIsIt a = new ThisIsIt();
a.f();
catch( Exception d )
System.out.println( "Doing something here" );
}That code won't even compile because :
Enam.java:21: unreachable statement
throw new Dua();
^
Enam.java:22: unreachable statement
throw new Tiga();
Do I interpret that question wrong????The problem you have is that when the code comes to the first 'throw' command it will throw the exception and exit the method (like a return does) so the code after will never be reached. In order to test your code you need to put some 'if's around the throws or give it a parameter from the console. eg.class ThisIsIt
public void f(int errorType) throws Satu, Dua, Tiga
if (errorType ==1)
throw new Satu();
if (errorType ==1)
throw new Tiga();
if (errorType ==1)
throw new Dua();
}Ted. -
Should this method throw an exception
Hi,
I have a method in a Database interface implementation class.
updateField( String fieldname, String value ) throws InvalidFieldException {
if ( ! is_Valid ( fieldname, value ) {
throw new InvalidFieldException();
}This will check the value does not exceed a certain length and it's format is correct, else it won't apply the update and should let the user know to correct the format of the value string.
is it good practice to have the method throw an InvalidFieldException() to return control to the calling method or how would you deal with an invalid field.
I know/ have heard that exceptions are for "Unexpected" things and a user entering data in the wrong format would not be classed as "unexpected" so by this definition using Exceptions is not the way to go.
Any ideas?This will check the value does not exceed a certain
length and it's format is correct, else it won't
apply the update and should let the user know to
correct the format of the value string.
is it good practice to have the method throw an
InvalidFieldException() to return control to the
calling method or how would you deal with an invalid
field.There are two strategies, both work. Just don't mix them:
- using contracts: clearly state that your method requires a certain range of values as an argument, and that everything outside this range will probably cause a problem. It's putting the responsibility of checking the argument's correctness to the caller, who anyway should know best how to provide the values and how to deal with wrong ones.
- defensive programming: take everything they give you and check yourself - throwing an IllegalArgumentException. Might be more secure, but far more work. I advise only to use this way on public methods, especially if you're going to distribute your classes as a library for others to use.
I know/ have heard that exceptions are for
"Unexpected" things and a user entering data in the
wrong format would not be classed as "unexpected" so
by this definition using Exceptions is not the way to
go.You're right, but there's a limit to what your method can do to fix the problem. If it can't do that by itself you need an escalation mechanism. Hence you can use an exception. -
I want to throw a NoSuchElementException if the next node that gets read does not exists but when I do so I get a NullPointerException. How do I fix this?
try {
Object o= currentNode.getData(); //this is where the nullexception happens
currentNode=currentNode.getNext();
return o;
catch (NoSuchElementException e) {
throw new NoSuchElementException();
}1. There is little sense catching a NoSuchElementException if you are just going to throw a new one (in the catch block)
2. Assuming currentNode is null
if (currentNode==null) throw new NoSuchElementException("currentNode is null");
return currentNode.getData(); -
Programmatically adding chart to a report throws exception
programmatically adding chart to a report throws exception "chart condition fields are not valid".
Configuration:
I am using CR4E to create web application, I've added RAS jars (rasapp.jar, rascore.jar, reporttemplate.jar, serialization.jar) to this web application. For designing reports i am using Crystal Reports 2008.
Code:
<%
// Get the previously opened report from the session.
ReportClientDocument reportClientDocument =
(ReportClientDocument)session.getAttribute("ReportClientDocument");
System.out.println(reportClientDocument.getReportDocument().getName());
// Try to get the report's DataDefinition object.
IDataDefinition dataDefinition;
try
dataDefinition = reportClientDocument.getDataDefController().getDataDefinition();
// If the DataDefinition object can not be retrieved, redirect the user to an error page.
catch (Exception e)
System.out.println("With error1");
return;
// Create a new ChartDefinition object and set its type to ChartType.group.
ChartDefinition chartDefinition = new ChartDefinition();
chartDefinition.setChartType(ChartType.group);
Get the conditional field of the report's first group. Set this conditional
field for the ChartDefinition object using the setConditonalFields method. Notice
that the conditional field is first placed in a Fields collection because the
setConditionalFields method takes a Fields object as an argument.
Fields conditionFields = new Fields();
if (!dataDefinition.getGroups().isEmpty())
IField field = dataDefinition.getGroups().getGroup(0).getConditionField();
System.out.println("Condition field name ->" + field.getLongName(Locale.ENGLISH));
conditionFields.addElement(field);
chartDefinition.setConditionFields(conditionFields);
//Get the summary field name from the form on the previous page.
String summaryFieldName = URLDecoder.decode(request.getParameter("summaryField"));
System.out.println("Summary field name ->" + summaryFieldName);
Loop through all of the report's summary fields until the one matching the name
above is found. Set this summary field for the ChartDefinition object using the
setDataFields method. Notice that the summary field is first placed in a Fields
collection because the setDataFields method takes a Fields object as an argument.
Fields dataFields = new Fields();
for (int i = 0; i < dataDefinition.getSummaryFields().size(); i++)
IField summaryField = dataDefinition.getSummaryFields().getField(i);
if (summaryField.getLongName(Locale.ENGLISH).equals(summaryFieldName))
System.out.println("Adding data field ->" + summaryFieldName);
dataFields.addElement(summaryField);
chartDefinition.setDataFields(dataFields);
Create a new ChartObject to represent the chart that will be added. Set the
ChartDefinition property of the ChartObject using the ChartDefinition object created
above.
ChartObject chartObject = new ChartObject();
chartObject.setChartDefinition(chartDefinition);
Get the chart type, chart placement, and chart title strings from the form on the
previous page. If no chart title was chosen, create a generic title.
String chartTypeString = request.getParameter("type");
String chartPlacementString = request.getParameter("placement");
String chartTitle = request.getParameter("title");
System.out.println("chartTypeString ->"+ chartTypeString + "<-chartPlacementString->" + chartPlacementString + "<-chartTitle->"+chartTitle);
if (chartTitle.equals(""))
chartTitle = "untitled";
Create a ChartStyleType object and a AreaSectionKind object based on the
the chartTypeString and chartPlacementString retrieved above. In this example
possible chart types are bar chart and pie chart. Possible chart placements
are header and footer.
ChartStyleType chartStyleType = ChartStyleType.from_string(chartTypeString);
AreaSectionKind chartPlacement = AreaSectionKind.from_string(chartPlacementString);
// Set the chart type, chart placement, and chart title for the chart.
chartObject.getChartStyle().setType(chartStyleType);
chartObject.setChartReportArea(chartPlacement);
chartObject.getChartStyle().getTextOptions().setTitle(chartTitle);
// Set the width, height, and top for the chart.
chartObject.setHeight(5000);
chartObject.setWidth(5000);
chartObject.setTop(1000);
Get a ReportDefController object that can be used to modify the report's definition.
ReportDefController reportDefController;
try
reportDefController = reportClientDocument.getReportDefController();
catch (Exception e)
System.out.println("With Error2");
return;
*Create a Section object that represents the section that will hold the chart.
If the chart placement was set header, get the header section, otherwise, if the
chart placement was set to footer, get the footer section.
Section chartSection = null;
if (chartPlacement.equals(AreaSectionKind.reportHeader))
IArea reportHeaderArea =
reportDefController.getReportDefinition().getReportHeaderArea();
chartSection = (Section)reportHeaderArea.getSections().getSection(0);
else if (chartPlacement.equals(AreaSectionKind.reportFooter))
IArea reportFooterArea =
reportDefController.getReportDefinition().getReportFooterArea();
chartSection = (Section)reportFooterArea.getSections().getSection(0);
Add the chart to the section using the ReportDefController object.
reportDefController.getReportObjectController().add(chartObject, chartSection, 1);
// Save the changes and close the report.
reportClientDocument.save();
reportClientDocument.close();
session.removeAttribute("ReportClientDocument");
%>
Trace:
com.crystaldecisions.sdk.occa.report.lib.ReportDefControllerException: The chart condition fields are not valid.---- Error code:-2147213287 Error code name:invalidChartObject
at com.crystaldecisions.sdk.occa.report.lib.ReportDefControllerException.throwReportDefControllerException(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.a(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.a(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.a(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.a(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.a(Unknown Source)
at com.crystaldecisions.sdk.occa.report.application.ReportObjectController.add(Unknown Source)
at org.apache.jsp.AddChart_jsp._jspService(AddChart_jsp.java:230)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:283)
at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:56)
at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:189)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:185)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:218)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:56)
at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:189)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:156)
at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:393)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:595)Please try this code snippet
var cs:ColumnSeries = new ColumnSeries();
cs.dataProvider = dp;
cs.displayName = "Series 2";
cs.yField = "values";
chart.series.push(cs);
OR
var temp:Array = [];
var cs:ColumnSeries = new ColumnSeries();
cs.dataProvider = dp;
cs.displayName = "Series 2";
cs.yField = "values";
temp = chart.series;
temp.add(cs);
chart.series = temp; -
Question about throws exception in interface and realized class
Hi,all
If I define a method In the interface like that-
public void Execute() throws NumberFormatException; In the realized class, I can define this method like that-
public void Execute() throws RuntimeException{
System.out.println("test");
}This is a right realization. But if I manage it to throws Exception or to throws Throwable in the class it leads a error. Why add this restrict only to Exception? What is the purpose of this way?
Greetings and thanks,
JasonWhen you say "throws NumberFormatException" you are really saying:
When using classes implementing this interface, you have to be prepared to deal with them throwing a NumberFormatException. Other exceptions won't happen.
When you come to implement it, it might not be possible for it to throw a NumberFormatException, so there's no reason why you should have to lie about that. Code handling it directly will be fine (it doesn't throw a NFE) and code handling it via the interface will be fine (it will handle NFEs, they just don't happen).
If your concrete implementation throws other sorts of exception, such as Exception or IOException, and so on, it's incompatible with code that's manipulating the interface. The interface says "NFEs might get thrown, nothing else will." while your implementation says "IOExceptions might get thrown".
So that explains why you can't use arbitrary exceptions. The special case is RuntimeException. RuntimeExceptions don't have to be caught, and it's expected that they can happen at any time - so there's no point trying to catch and handle them as a general case.
The classic example of a RuntimeException is a NullPointerException. You don't need to declare your method as throwing a NullPointerException even though it might get thrown. And you don't have to add NullPointerException to the throws part of the interface definition, because you already know that the concrete implementation could throw a NPE at any time.
Hope that helps (a little).
I'd recommend reading the API documentation on RuntimeException and Exception to get a clearer insight into this.
Dave. -
Hi all ... I'm facing with a really simple program that says
Create a class called "MyClass" and construct three methods named "abs"
(i) to find the absolute value of an integer
(ii) to find the absoute value of a float
(iii)to find the absolute value of a double
I'm a few days old in java .. so if my coding methodologies are too poor please bear with me..
import java.io.*;
class MyClass
static int abs(int i)
return((i>0) ? i : (-i));
static float abs(float f)
return((f>0) ? f : -f);
static double abs(double d)
return((d>0) ? d : -d);
public static void getData() throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try
String inputInt = br.readLine();
int integerValue = Integer.parseInt(inputInt);
System.out.println(abs(integerValue));
catch(NumberFormatException noe)
try
String inputFloat = br.readLine();
float floatValue = Float.parseFloat(inputFloat);
System.out.println(abs(floatValue));
catch(NumberFormatException noe1)
String inputDouble = br.readLine();
double floatValue = Double.parseDouble(inputDouble);
System.out.println(abs(floatValue));
catch(IOException ioe1)
System.out.println(ioe1.getMessage());
public static void main(String[] args)
System.out.println("This would gve absoulte value of an integer, float, or double ... go ahead, enter something ");
getData();
}This generates the following compilation error ...
neo@tathagata:~/Java Progs/assignment$ javac MyClass.java
1. ERROR in MyClass.java
(at line 62)
catch(IOException ioe1)
^^^^^
Syntax error on token "catch", Identifier expected
----------Now upto what I have read and understood if I have an exception that may arise anywhere in a method ...an IOException say, I can write
method() throws IOException
but when I write like this it generates a compiler error saying
1. ERROR in MyClass.java
(at line 70)
getData();
^^^^^^^^^
Unhandled exception type IOException
then again when I add a catch with it like
method() throws IOException
//do something
catch(IOException ioe)
System.out.println(e.getMessage());
1. ERROR in MyClass.java
(at line 62)
catch(IOException ioe1)
^^^^^
Syntax error on token "catch", Identifier expected
I'm not being able to Google where I'm going wrong ... it would be great if anybody can point out my mistakes ...
Thanks in advance
java.version=1.5.0_06
java.vm.version=1.5.0_06-b05
java.runtime.version=1.5.0_06-b05
java.vendor=Sun Microsystems Inc.
os.name=Linux
os.version=2.6.12-10-386
os.arch=i386thanks dood .. I'm sorry to post such an error but the problem still it presists
Currently ...
public static void getData() throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try
String inputInt = br.readLine();
int integerValue = Integer.parseInt(inputInt);
System.out.println(abs(integerValue));
catch(NumberFormatException noe)
try
String inputFloat = br.readLine();
float floatValue = Float.parseFloat(inputFloat);
System.out.println(abs(floatValue));
catch(NumberFormatException noe1)
String inputDouble = br.readLine();
double floatValue = Double.parseDouble(inputDouble);
System.out.println(abs(floatValue));
catch(IOException ioe1)
System.out.println(ioe1.getMessage());
ioe1.printStackTrace();
}the error I'm getting is
1. ERROR in MyClass.java
(at line 73)
getData();
^^^^^^^^^
Unhandled exception type IOException
1 problemI want one confirmation ... when one method throws an exception what exactly happens to the catch part ...I guess I should read more on eceptions before throwing them in the forum.
thanks again for helping ...
Maybe you are looking for
-
I can't get Itunes to back up my Iphone 4. It doesn't matter if i try to sync it or do it manually. It says (translated from danish): Itunes couldn't back up your iphone, because the back up file is broken or doesn't "fit" Iphone. I have already trie
-
This is a follow-up to Re-authenticate or provide additional credentials to access sensitive data. We are currently looking at implementing NWSSO. As far as I know, NWSSO can't be used as an external security product for Digital Signatures so that us
-
JBIG2 files open only after 'rebuilding'....
I use a third party app to generate PDF files using JBIG2 compression. I notice unusual behavior in Adobe Acrobat 8 Standard that does not occur in 9 or 10 (Std or Pro). When v8 opens these files, it performs a "Rebuilding" process before the file is
-
What is the best setting for exporting an HD sequence as DV?
I want to make sure that my end product is the highest quality and for some reason I don't think I am getting it. when I play it on my big screen, it doesn't look sharp. I am doing a project weekly that has 3 movies; one is nothing but pictures trasi
-
Hi, I have installed a new domain with NSM. The 'NSM Schema Utility' is showing: Screenshot.png But in the NSM Admin I have the message: "Schema Not Extended" Can I verify with for ex. the mmc 'Active Directory Schema' if the all required extensions