SetFont throws ArithmeticException: / by zero

Hello,
I'm trying to properly display cp437 text file. I have found [perfect font|http://www.dafont.com/perfect-dos-vga-437.font] for this purpose. Loading font using Font.createFont is working, but when it should be used by calling jTextArea.setFont, it throws few times ArithmeticException. Font is working properly when it is installed to windows/fonts folder.
Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero
        at javax.swing.text.PlainView.paint(PlainView.java:256)
        at javax.swing.plaf.basic.BasicTextUI$RootView.paint(BasicTextUI.java:1422)
        at javax.swing.plaf.basic.BasicTextUI.paintSafely(BasicTextUI.java:722)
        at javax.swing.plaf.basic.BasicTextUI.paint(BasicTextUI.java:869)
        at javax.swing.plaf.basic.BasicTextUI.update(BasicTextUI.java:848)
        at javax.swing.JComponent.paintComponent(JComponent.java:763)
        at javax.swing.JComponent.paint(JComponent.java:1029)
        at javax.swing.JComponent.paintChildren(JComponent.java:864)
        at javax.swing.JComponent.paint(JComponent.java:1038)
        at javax.swing.JViewport.paint(JViewport.java:747)
        at javax.swing.JComponent.paintChildren(JComponent.java:864)
        at javax.swing.JComponent.paint(JComponent.java:1038)
        at javax.swing.JComponent.paintChildren(JComponent.java:864)
        at javax.swing.JComponent.paint(JComponent.java:1038)
        at javax.swing.JComponent.paintChildren(JComponent.java:864)
        at javax.swing.JComponent.paint(JComponent.java:1038)
        at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
        at javax.swing.JComponent.paintChildren(JComponent.java:864)
        at javax.swing.JComponent.paintToOffscreen(JComponent.java:5131)
        at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1475)
        at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1406)
        at javax.swing.RepaintManager.paint(RepaintManager.java:1220)
        at javax.swing.JComponent.paint(JComponent.java:1015)
        at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
        at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
        at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
        at java.awt.Container.paint(Container.java:1780)
        at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
        at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
        at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
        at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

It's weird. I dont think it's my fault. Look...
* To change this template, choose Tools | Templates
* and open the template in the editor.
* NewJFrame.java
* Created on 8.9.2009, 19:50:52
package fonttest;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
* @author filuta
public class NewJFrame extends javax.swing.JFrame {
    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        try {   
            Font dosfont = Font.createFont(Font.TRUETYPE_FONT,
                    new File("C:\\Users\\filuta\\Downloads\\dos437\\" +
                    "Perfect DOS VGA 437.ttf")).deriveFont(12f);
            jTextArea1.setFont(dosfont);
        catch (FontFormatException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        catch (IOException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
        pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}

Similar Messages

  • Error : java.lang.ArithmeticException:/ by zero

    Hi ,
    i don't know what 's wrong with my program
    i call applet in jar file when it call applet it show
    applet initailize and show background color
    and show java.lang.ArithmeticException:/ by zero
    i don't understand how this exception mean??
    in my servlet never use / to do anything
    any idea??

    The Exception is thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.
    Post ur Applet code so that we can analyse

  • OCI, java.lang.ArithmeticException: / by zero

    Hi,
    Could someone help me with this?
    I'm using OCI driver, because database character set is user-defined.
    There is no problem with connection, but if I open any database objects list or execute any statement I've got this exception:
    Oracle SQL Developer 1.5.5:
    java.lang.ArithmeticException: / by zero
         at oracle.jdbc.driver.OraclePreparedStatement.<init>(OraclePreparedStatement.java:1245)
         at oracle.jdbc.driver.OracleCallableStatement.<init>(OracleCallableStatement.java:100)
         at oracle.jdbc.driver.T2CCallableStatement.<init>(T2CCallableStatement.java:103)
         at oracle.jdbc.driver.T2CDriverExtension.allocateCallableStatement(T2CDriverExtension.java:96)
         at oracle.jdbc.driver.PhysicalConnection.prepareCall(PhysicalConnection.java:3430)
         at oracle.jdbc.driver.PhysicalConnection.prepareCall(PhysicalConnection.java:3377)
         at oracle.dbtools.db.DBUtil.executeReturnOneCol(DBUtil.java:275)
         at oracle.dbtools.raptor.InitializeConnectionListener.initConnection(InitializeConnectionListener.java:137)
         at oracle.dbtools.raptor.InitializeConnectionListener$1.run(InitializeConnectionListener.java:85)
    Oracle SQL Developer 2.1.1.64:
    Level Sequence Elapsed Message
    SEVERE     99     2448498          / by zero
    I dig into JVM using VisualVM and find out that oracle.jdbc.driver.T2CConnection.conversion (DBConversion.java) has property sMaxCharSize=0.
    When I'm connecting to other DB (wihtout user defined charset) this property has value 1 and everything is ok.
    Other DB tools like Squirell SQL, PL/SQL Developer works fine so maybe there is a bug in Oracle SQL Developer?.

    This seems more like a bug in the JDBC driver than in SQL Developer itself.
    Try replacing the JDBC driver in SQLDEVELOPER_INSTALL_DIR\jdbc\lib with the very latest version from OTN.
    You may also want to try upgrading your OCI client to latest and if you still got the problem then better raise a SR on Metalink/MOS if you have a DB support contract.

  • Error: java.lang.ArithmeticException: / by zero on SQLDEVELOPER

    Hello, I have SQLdevoleper 3.1, Java JDK 1.6.0.30. Connect to Oracle data base 10g is successfully. But when i open a table, i receive the following:
    java.lang.ArithmeticException: / by zero
         at oracle.jdbc.driver.OraclePreparedStatement.<init>(OraclePreparedStatement.java:1291)
         at oracle.jdbc.driver.T4CPreparedStatement.<init>(T4CPreparedStatement.java:29)
         at oracle.jdbc.driver.T4CDriverExtension.allocatePreparedStatement(T4CDriverExtension.java:67)
         at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3523)
         at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3409)
         at oracle.dbtools.raptor.controls.grid.OracleRSTModel.prepareStatement(OracleRSTModel.java:81)
         at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.openResultSet(ResultSetTableModel.java:458)
         at oracle.dbtools.raptor.controls.grid.ResultSetTableModel.fetchNext(ResultSetTableModel.java:183)
         at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:636)
         at oracle.dbtools.raptor.controls.grid.ResultSetTableModel$4.doWork(ResultSetTableModel.java:620)
         at oracle.dbtools.raptor.backgroundTask.RaptorTask.call(RaptorTask.java:193)
         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
         at java.util.concurrent.FutureTask.run(FutureTask.java:138)
         at oracle.dbtools.raptor.backgroundTask.RaptorTaskManager$RaptorFutureTask.run(RaptorTaskManager.java:515)
         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
         at java.util.concurrent.FutureTask.run(FutureTask.java:138)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:662)
    and when I enter SELECT (select sysdate from dual), the result returns "/ by zero"
    How to solve this problem? Tell me who can, please.

    Proceed as follows:
    1. Start sqldeveloper.
    2. Go to Tools-->preferences-->database-->NLS parameters.
    3. Change LANGUAGE to AMERICAN.
    4. Restart sql developer.
    Not help. What more can I do?

  • Is anyone having issues with Android version 4.3 for Galaxy III throwing in zeroes into text messages?

    I received a message on Christmas Eve that a free update was available for my Samsung Galaxy III.  I accepted the download and discovered some enhancements and fixes that I liked (finally, my voicemail icon displays the number of waiting voicemails that I have!) but I've noticed to glaring issues:
    1. When I send text messages that include numbers (a phone number for example) the OS throws in random zeroes into the number.  I have to usually touch the ENTER key and type the number on a new line and play around with it until the number stays in the message correctly.
    2. I've had occasional lockups using the media hub which, when I do a restart, causes my settings to revert to the default factory settings....kind of a pain.
    There may be other issues. 
    Q. Has anyone out there experienced this same thing?
    Q. Is Google going to fix these issues?  I noticed that on Christmas day a half dozen or so updates were made, but these to things still are a problem. 
    Q. Also, the Verizon Wireless Software Upgrade Assistant on my laptop insists that my version is not supported.  I can still access photos and music, but it's a little annoying...

        I'm sorry you're having issues with your phone after your update BigLouie1124. I recommend enabling safe mode to see if any of your apps are causing issues with your new software. If so, you can remove them. Here are the steps http://vz.to/1cD0kqT . If you continue to have issues the last step would be a factory reset to clear up some of your issues http://vz.to/JCsr33 . Please keep us posted and continue to clear unwanted message threads and clear your browser history periodically.
    KinquanaH_VZW
    Follow us on Twitter @vzwsupport

  • Purpose of throws clause in exception handling

    hi all,
    I have written a sample code for exception handling...please refer below....
    class a
    void fun() throws ArithmeticException
    int i=0;
    i=10/0;
    class exec
    public static void main(String a[])
    a a1=new a();
         try{a1.fun();}
         catch(ArithmeticException e){System.out.println("hi");}
    }

    I read the article...and came out with these points...
    1..If method is throwing an unchecked exception (as in this case) then there is no need for throws clause, if you are not catching it then and there only.....
    2...if a method is throwing a checked exception then either you need to catch it then and there only or you must specify a throws clause for the same in function definition......*And the purpose of not catching it then and there only is*
    "For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it."
    M I RIGHT??

  • What does LabView do if the integral time constant is set to zero in the PID vi?

    Why is zero a valid entry for the integral time constant in the PID vi?

    I am not familiar with the PID toolkit but I imagine that rather than throwing an error, zero and negative values are ignored. The best place to see what is going on is to open the VI up and see how it treats this parameter.

  • / by zero exception

    Hi all,
    Double infi = new Double(1/0.);
    Can somebody tell me why doesnt the above statement throw a '/ by zero' exception?

    for your information, doubles cant actually store values up to infinity. they just store really high numbers and if you dont know this already, 1 or any other number/0 is infinity hence an exception

  • How to add a blank row into a datatable

    i hava adatatable which contains the datas from database.i need to add a new data so that i need a blank row which contain the same number of columns in the existing datatable.
    Pls Help..

    sorry i am a beginner in jsf..
    In the crud Example i saw a code in MyCrudBean.java.i wrote the code like that but the same stage only one row is coming i cant add n items .
    * Department.java
    * Created on Nov 22, 2007, 4:43:12 PM
    package datatable;
    import Item.DeptDatabase;
    import com.sun.rave.web.ui.appbase.AbstractPageBean;
    import com.sun.webui.jsf.component.Body;
    import com.sun.webui.jsf.component.Form;
    import com.sun.webui.jsf.component.Head;
    import com.sun.webui.jsf.component.Html;
    import com.sun.webui.jsf.component.Link;
    import com.sun.webui.jsf.component.Page;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.faces.FacesException;
    import javax.faces.component.html.HtmlDataTable;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    public class Department extends AbstractPageBean {
    Connection con = null;
    PreparedStatement StmtRateSel = null;
    ResultSet rs = null;
    private List<DeptDatabase> list = new ArrayList();
    private int addCount = 1;
    private HtmlDataTable myDataTable;
    private static final int DEFAULT_TABLE_ROWS = 10;
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    * <p>Automatically managed component initialization. <strong>WARNING:</strong>
    * This method is automatically generated, so any user-specified code inserted
    * here is subject to being replaced.</p>
    private void _init() throws Exception {
    private Page page1 = new Page();
    public Page getPage1() {
    return page1;
    public void setPage1(Page p) {
    this.page1 = p;
    private Html html1 = new Html();
    public Html getHtml1() {
    return html1;
    public void setHtml1(Html h) {
    this.html1 = h;
    private Head head1 = new Head();
    public Head getHead1() {
    return head1;
    public void setHead1(Head h) {
    this.head1 = h;
    private Link link1 = new Link();
    public Link getLink1() {
    return link1;
    public void setLink1(Link l) {
    this.link1 = l;
    private Body body1 = new Body();
    public Body getBody1() {
    return body1;
    public void setBody1(Body b) {
    this.body1 = b;
    private Form form1 = new Form();
    public Form getForm1() {
    return form1;
    public void setForm1(Form f) {
    this.form1 = f;
    // </editor-fold>
    * <p>Construct a new Page bean instance.</p>
    public Department() {
    public void deptsave() throws SQLException{
    connection();
    StmtRateSel      = con.prepareStatement("execute prcPnsDepartmentIns");
    rs = StmtRateSel.executeQuery();
    con.close();
    @Override
    public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // before managed components are initialized
    // TODO - add your own initialiation code here
    // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
    // Initialize automatically managed components
    // Note - this logic should NOT be modified
    try {
    _init();
    } catch (Exception e) {
    log("Department Initialization Failure", e);
    throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
    // </editor-fold>
    // Perform application initialization that must complete
    // after managed components are initialized
    // TODO - add your own initialization code here
    * <p>Callback method that is called after the component tree has been
    * restored, but before any event processing takes place. This method
    * will <strong>only</strong> be called on a postback request that
    * is processing a form submit. Customize this method to allocate
    * resources that will be required in your event handlers.</p>
    @Override
    public void preprocess() {
    * <p>Callback method that is called just before rendering takes place.
    * This method will <strong>only</strong> be called for the page that
    * will actually be rendered (and not, for example, on a page that
    * handled a postback and then navigated to a different page). Customize
    * this method to allocate resources that will be required for rendering
    * this page.</p>
    @Override
    public void prerender() {
    * <p>Callback method that is called after rendering is completed for
    * this request, if <code>init()</code> was called (regardless of whether
    * or not this was the page that was actually rendered). Customize this
    * method to release resources acquired in the <code>init()</code>,
    * <code>preprocess()</code>, or <code>prerender()</code> methods (or
    * acquired during execution of an event handler).</p>
    @Override
    public void destroy() {
    * <p>Return a reference to the scoped data bean.</p>
    * @return reference to the scoped data bean
    protected SessionBean1 getSessionBean1() {
    return (SessionBean1) getBean("SessionBean1");
    * <p>Return a reference to the scoped data bean.</p>
    * @return reference to the scoped data bean
    protected RequestBean1 getRequestBean1() {
    return (RequestBean1) getBean("RequestBean1");
    * <p>Return a reference to the scoped data bean.</p>
    * @return reference to the scoped data bean
    protected ApplicationBean1 getApplicationBean1() {
    return (ApplicationBean1) getBean("ApplicationBean1");
    private void connection() {
    try{
    Context ctx = new InitialContext();
    System.out.println("context"+ctx);
    if(ctx == null )
    throw new Exception("Boom - No Context");
    DataSource ds = (DataSource)ctx.lookup("BiteRiteJNDI");
    if (ds != null) {
    con = ds.getConnection();
    System.out.println("connnn"+con);
    catch(Exception e)
    {System.out.println(e);}
    public void addDataItem() {
    while (addCount-- > 0) {
    DeptDatabase myNewDataItem = new DeptDatabase();
    //myNewDataItem.setEditMode(true);
    list.add(myNewDataItem);
    //log(myDataList);
    // Reset counter and go to last page.
    addCount = 1;
    // log(myDataList);
    // Reset counter and go to last page.
    //addCount = DEFAULT_ADD_COUNT;
    pageLast();
    System.out.println("in add itm");
    // list.add(new DeptDatabase());
    public List getListtt(){
    return list;
    public HtmlDataTable getMyDataTable() {
    if (myDataTable == null) {
    myDataTable = new HtmlDataTable();
    myDataTable.setRows(DEFAULT_TABLE_ROWS);
    return myDataTable;
    private static void log(Object object) {
    System.out.println("bejoy"+new Exception().getStackTrace()[1].getMethodName() + ": " + object);
    public void pageLast() {
    System.out.println("in Page last");
    int count = myDataTable.getRowCount();
    System.out.println("count"+count);
    int rows = myDataTable.getRows();
    System.out.println("rows"+rows);
    if (rows != 0) { // Prevent ArithmeticException: / by zero.
    System.out.println("not equals zero");
    myDataTable.setFirst(count - ((count % rows != 0) ? count % rows : rows));
    log(new Integer(myDataTable.getFirst()));
    public void setListtt(List<DeptDatabase> list) {
    this.list = list;
    * CRUD table: set datatable.
    * @param myDataTable The datatable.
    public void setMyDataTable(HtmlDataTable myDataTable) {
    this.myDataTable = myDataTable;
    jsp
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    Document : Department
    Created on : Nov 22, 2007, 4:43:11 PM
    Author : Administrator
    -->
    <jsp:root version="2.1" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
    <jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>
    <f:view>
    <webuijsf:page binding="#{Department.page1}" id="page1">
    <webuijsf:html binding="#{Department.html1}" id="html1">
    <webuijsf:head binding="#{Department.head1}" id="head1">
    <webuijsf:link binding="#{Department.link1}" id="link1" url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body binding="#{Department.body1}" id="body1" style="-rave-layout: grid">
    <webuijsf:form binding="#{Department.form1}" id="form1">
    <h:dataTable binding="#{Department.myDataTable}" id="myDataTable" value="#{Department.listtt}" var="dataItem">
    <h:column>
    <f:facet name="header">
    <h:outputText value="Departments"/>
    </f:facet>
    <h:inputText value="#{dataItem.department}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="StockItem"/>
    </f:facet>
    <h:inputText value="#{dataItem.stockItem}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="StockUnit"/>
    </f:facet>
    <h:inputText value="#{dataItem.stockUnit}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="MaxStock"/>
    </f:facet>
    <h:inputText value="#{dataItem.maxStock}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="MinStock"/>
    </f:facet>
    <h:inputText value="#{dataItem.minStock}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="ReorderLevel"/>
    </f:facet>
    <h:inputText value="#{dataItem.reorderlevel}"/>
    </h:column>
    </h:dataTable>
    <h:commandButton action="#{Department.addDataItem}" value="Add"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
    </webuijsf:page>
    </f:view>
    </jsp:root>
    i dont know wats the problem??
    pls send a sample code to add n items

  • Problem accessing exception object in jsp error page - Apache Tomcat 5.0.25

    Hi all,
    I'm thoroughly confused and need some help. I've deployed a very simple web application in Apache Tomcat 5.0.25 to test exception handling - errortest.jsp and error.jsp. errortest.jsp throws a divide by zero exception if executed with default values in text fields.
    When I put the directive IsErrorPage="true" in error.jsp i get a HTTP 500 error when error.jsp is accessed. If I remove it error.jsp is displayed but I cant access the exception object - if I try to I get an exception below:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 5 in the jsp file: /error.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    E:\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mywebapp\org\apache\jsp\error_jsp.java:46: cannot resolve symbol
    symbol : variable exception
    location: class org.apache.jsp.error_jsp
    out.print(exception.getMessage());
    ^
    1 error
    Below is the code for the two jsp pages:
    errortest.jsp:
    <%@ page errorPage="error.jsp" %>
    <html>
    <head><title>Error test</title></head>
    <body>     
         <form action="errortest.jsp" method="post">
         Enter first number:<input type="text" name="first" value="5"/><br>
         Enter second number:<input type="text" name="second" value="0"/><br>
         <input type="submit"/>
         </form>
         <%
         if (request.getMethod().equals("POST")) {
              int first = Integer.parseInt( request.getParameter( "first" ) );
              int second = Integer.parseInt( request.getParameter( "second" ) );
              int answer = first/second;
         %>
    </body>
    </html>
    NB: I am able to catch and display the exception if I use a try/catch block around the division as shown below.
    try {
    int answer = first/second;
    } catch( Exception e) {
    e.printStackTrace( new PrintWriter(out) );
    error.jsp (first draft)
    NB: HTTP 500 error occurs when directive "isErrorPage" is added:
    <%@ page isErrorPage="true" %>
    <html>
    <head><title>Error Page</title></head>
    <body>
    </body>
    </html>
    error.jsp (second draft)
    NB: directive is removed but exception thrown when implicit exception object is accessed. error.jsp displays if exception object is not accessed:
    <%@ page %>
    <html>
    <head><title>Error Page</title></head>
    <body>
    <%=exception.getMessage()%>
    </body>
    </html>
    Web server specs:
    Apache Tomcat 5.0.25
    Machine specs:
    Windows XP Pro
    Java environments:
    j2sdk1.4.2_03
    J2EE 1.4

    This works for me:
    throwError.jsp
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <%@ page language="java" errorPage="/error.jsp"
    contentType="text/html; charset=utf-8" %>
    <html>
    <head>
         <title>Throw Exception</title>
    </head>
    <body>
    Throwing exception....
    <%
    // throw ArithmeticException
    int badInt = 12/0;
    %>
    </body>
    </html>
    error.jsp
    <%@ page language="java" isErrorPage="true" %>
    <head><title>Doh!</title></head>
    An Error has occurred in this application.
    <% if (exception != null) { %>
    <pre><% exception.printStackTrace(new java.io.PrintWriter(out)); %></pre>
    <% } else { %>
    Please check your log files for further information.
    <% } %>

  • Exception during event processing

    I have an application which has an "exception catcher" at the bottom that performs some "exit work" that I need done when the program terminates abnormally.
    In certain places of the program, I automatically have the program quit and exit by dividing by zero to trigger an exception. Up until today, this technique has worked nicely.
    Today, however, I tried to do it in the middle of an AWT Event (a menu selection from a frame), in the following method:
    public void actionPerformed(ActionEvent event)
    Instead of the exception being handled by my routine, the program instead hangs without getting to the "catch" command that I usually use and instead generates the following sequence of error messages:
    Exception occurred during event dispatching:
    java.lang.ArithmeticException: / by zero
    at WTPFrame.actionPerformed(wtp.java:5335)
    at java.awt.AWTEventMulticaster.actionPerformed(Unknown Source)
    at java.awt.MenuItem.processActionEvent(Unknown Source)
    at java.awt.MenuItem.processEvent(Unknown Source)
    at java.awt.MenuComponent.dispatchEventImpl(Unknown Source)
    at java.awt.MenuComponent.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Is there any thing I can do to allow this exception to pass through to my handler so that the program doesn't hang?
    Thanks,
    Bruce

    When I was describing the business of subclassing an exception, this was independent of your hanging problem.
    The hanging thing is a consequence of the way that threading is done in a GUI application.
    Your app (by the sound of it) has two threads of execution running. The "main" thread is listening to the socket and running the game. The "EventDispatcher" thread is listening to the mouse and keyboard and redrawing the GUI.
    When a GUI event handler is called, this call is done by the event dispatcher thread. If you throw an exception from the handler, the loop in the event dispatcher thread just prints the stack trace and goes on listening for more mouse and keyboard events.
    To get the threads to communicate, you need for one thread to set a flag that the other thread can read. To interrupt the socket read, you need to call interrupt on the main thread from the gui thread. Lastly, to get the app to exit you must call System.exit().
    class Foo {
      volatile boolean weHaveToExit = false;
      Thread mainThread;
      // this method is called when the user clicks the exit button
      void exitMenuHandler() {
        weHaveToExit = true;
        mainThread.interrupt();
      public static void main(String[] av) {
        mainThread = Thread.currentThread();
        // create the menu
        // attach the event handler to it
         while(!weHaveToExit) {
             // process a game move
         System.exit(0);

  • Unchecked exception

    hi all...
    can throws be used to avoid unchecked exception???
    for example,,,,,in this c ode throws is not able to handle unchecked exception i.e. arithmetic exception.....
    public class Test {
    public static void main(String[] args) throws ArithmeticException{
    int a=1,b=0,c;
    c=a/b;
    System.out.println(c);
    but This code is working fine ,,,when i am using try catch to handle this exception
    public class test1 {
    public static void main(String[] args) {
    try{
    int a=1,b=0,c;
    c=a/b;
    System.out.println(c);}
    catch(ArithmeticException e)
    System.out.println("error occured");
    ..........................

    The throws clause doesn't handle an exception, it warns the caller of the method that there's a checked exception that the code that calls it needs to deal with.
    Unchecked exceptions (e.g zero divide) are usually not handled, they typically cause the program to abnormally terminate. That's because, as a general rule, an unchecked exception means there's something wrong with the program so what's the point of continuing?
    A checked, exception, on the other hand, usually indicates that there's something wrong with the program's environment. A data file is missing or has the wrong format, the user has entered something other than a number where a number is expected or something of that kind, and it often makes sense for the program to try and recover (e.g. by asking for the data again).

  • Why does SunOne 6.1 call servlet init() method twice on startup

    Hi,
    SunOne6.1 sp 5 is running my servlet's init() method twice when I put load-on-startup in the web-xml file. Is this a known problem and is there a work around as no amount of synchronising seems to work.
    I'm running 2.3.dtd for the default_web.xml file and my entries look like this :-
    <servlet>
    <servlet-name>RelatisLogin</servlet-name>
    <servlet-class>com.MyServlet</servlet-class>
    <load-on-startup>7</load-on-startup>
    </servlet>
    This init method only contains a basic check at the moment :-
    public void init()
    System.out.println("init.....");
    If I take <load-on-startup> away and run the server then call the servlet via the url it only runs init once.
    I've tried synchronizing the block but this doesn't work.
    The synchonization code I used looks like this:-
    public void init(ServletConfig config) throws ServletException
    synchronized( AnotherClass.staticString )
    if ( AnotherClass.staticString.length() > 0 ) return;
    System.out.println( AnotherClass.staticString.length() );
    AnotherClass.staticString = "init has been called";
    try
    int i = 0;
    i = i/i;
    } catch(Exception e)
    e.printStackTrace();
    The declaration of "AnotherClass.staticString" is :-
    public static String staticString = "";
    The output of "System.out.println( AnotherClass.staticString.length() );" is 0 and displayed twice.
    I deliberately cause a divide by zero error to get a stack trace so that i can determine what called init(), the stack trace is printed twice and is always :-
    java.lang.ArithmeticException: / by zero
    at com.MyServlet.init(MyServlet.java:47)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:921)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:813)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3478)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:3760)
    at com.iplanet.ias.web.WebModule.start(WebModule.java:251)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1133)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:652)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1133)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:355)
    at org.apache.catalina.startup.Embedded.start(Embedded.java:995)
    at com.iplanet.ias.web.WebContainer.start(WebContainer.java:431)
    at com.iplanet.ias.web.WebContainer.startInstance(WebContainer.java:500)
    at com.iplanet.ias.server.J2EERunner.confPostInit(J2EERunner.java:161)
    It looks like SunOne starts then calls init() and then restarts and calls init() again.
    The same code and same web.xml entries work fine in Tomcat 5, init() only every gets called once.
    Any ideas? Can I post this as a bug?
    Thanks in advance for any help.
    Chris.

    Sorry to have not replied to this thread earlier.....forgot all about it.
    The reason init was being called twice by IPanet (Sun One) is IPanet comes with a default context called "Search" already in server.xml file.
    This context was loading all the classes on my class path and this causing "init" to run. Then my context entry also loaded all the files in the class path.
    Quite why Sun include this "Search" context is beyond me......annoying. If you take it out the the problem goes away.
    Basically if you leave this in then your running to web servers (JVM's) your one and Sun's stupid "Search" one. As they are separate JVM's no amount of synchronisation would ever fix it.

  • Finally cause Exception be forgotten

    In trying out that finally cause previous return value be forgotten, as described on page 206 of "The Java Programming Language, 3rd edition", I wrote the following code, and tested it with jdk1.3.1. To my supprise, not only the return value was forgotten, the exception was appeared forgotten as well:
    class PException extends Exception {
    class Final {
        void f1(int i) {
         int result;
         System.out.println("f1("+i+")");
         try {
             result = f2(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
         try {
             result = f3(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
        int f2(int i) throws PException {
         try {
             if (i == 1) {
              System.out.println("generate exception");
              throw new PException();
             return 1;
         } finally {
             return 2;
        int f3(int i) throws PException {
         if (i == 1) {
             System.out.println("generate exception");
             throw new PException();
         return 1;
        public static void main(String[] args) {
         Final f = new Final();
         f.f1(1);
         f.f1(2);
         f.f1(1);
    }Here is the result:
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException
    f1(2)
    result = 2
    result = 1
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException

    The concern here is that when the
    try {
    finally {
    }pattern is used, without the catch block, purelly for flow control purpose, a return statement in the finally block could be problematic. If a finally block ends with a return statement, any exception that might be thrown in the try block would be ignored. The unhandled exception will not propergate, it simply lost in the midst. Because any code could throw unchecked exception, if the exception cannot afford to be lost, then one should be careful not to use return in the finally block. See the following test code:
    class Finally {
        void test() {
         int result;
         System.out.println("test()");
         try {
             result = f1();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             result = f2();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f3();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f4();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
        int f1() {
         System.out.println("f1()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return b; // this return clobber the unchecked exception
        int f2() {
         System.out.println("f2()");
         int a = 0;
         int b = 0;
         a = 1/0; // this generate an unchecked exception
         b = 1;
         return b;
        void f3() {
         System.out.println("f3()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return;   // this return clobber the unchecked exception
        void f4() {
         System.out.println("f4()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
        public static void main(String[] args) {
         Finally f = new Finally();
         f.test();
    /code]
    Here are the results:test()
    f1()
    result = 0
    f2()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    f3()
    f4()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    We see that the devide by zero exception throw by f1() simply vanished, the unintended result 0, instead of the intended result 1, is returned. The test() method did not detect any abnormality in f1(), which is scary. To drive the point home, we try f3() and f4(), which has void return type. A simple return statement in f3() causes exception be lost. The stack frame seems intact, for otherwise, the test() method would exit abruptly before f2() even get a chance to be called.

  • NetBeans problem with Keyboard class wann't compile

    Hi everyone I'm trying run my program in NetBeans and i have two classes main one A1Q2 and Keyboard2. In main class NetBeans is seing that can not find Keyboard2 class . So everywhere where is Keyboard2 compiler highlited this for red color - red line. I can not figure out what is wrong. Please for any help . Apropos i've been using NetBeans from yeasterday.
    public class A1Q2 {
         public void start(){
              test01();
              try{
              test02();
              System.out.println("Statement A");
              } catch(ArrayIndexOutOfBoundsException e){
                             System.out.println("CAUGHT" + e.toString());
              System.out.println();
              System.out.println("    TEST 3A.  An exception occurs when the user");
              System.out.println("    enters the number 7.");
              System.out.println();
              test03();
              System.out.println();
              System.out.println("    TEST 3B.  An exception occurs when the user");
              System.out.println("    first enters a number which is not 7");
              System.out.println("    and, at the prompt, enters a String");
              System.out.println("    containing non numerical characters");
              System.out.println();
              test03();
              System.out.println("Finished");
         private void test01() {
              String word1;
              System.out.println("    TEST 1.  An exception occurs when the user");
              System.out.println("    enters a String with more than 2 characters.");
              System.out.println();
              System.out.print("Enter a String with less than 3 characters: ");
              try{
                   String word2 = Keyboard2.readInput();
                   if (word2.length() < 3) {
                        word1 = word2;
                   } else {
                        word1 = null;
                        throw new NullPointerException();
                   int len = word1.length();
                   System.out.println("Statement B");
              } catch(NullPointerException e){
                   System.out.println("CAUGHT:" + e.toString());
         private void test02() {
              int[] numbers = { 4, 6, 7, 3, 2 };
              System.out.println();
              System.out.println("    TEST 2.  An exception occurs when the user");
              System.out.println("    enters a number < 0 or > 4");
              System.out.println();
              System.out.print("Enter a number which is between 0 and " + (numbers.length-1) + " (inclusive): ");
                   int pos = Integer.parseInt(Keyboard2.readInput());
                   if(!(pos >=0 && pos <= 4)){
                        throw new ArrayIndexOutOfBoundsException(":" + pos);
                   System.out.println("Number: " + numbers[pos]);
                   System.out.println("Statement C");
         private void test03() {
              try{
                   System.out.print("Enter any number except 7: ");
                   int num2 = Integer.parseInt(Keyboard2.readInput() + 1);
                   if(num2 == 71){
                        throw new ArithmeticException("/ by zero");
                   int num1 = 255 / (num2 - 71);
              try{
                   System.out.print("Enter a String of digits: ");
                    String numS = Keyboard2.readInput();
                   int num3 = Integer.parseInt(numS);
                    if(!(num3> 0)){
                         throw new NumberFormatException("For input string: " + "\"" +numS +"\"");
              System.out.println("Statement D");
              } catch(NumberFormatException e){
                   System.out.println("CAUGHT:" + e.toString());
              } catch (ArithmeticException e){
                   System.out.println("CAUGHT:" + e.toString());
              System.out.println("Statement E");
    //----------- MAIN METHOD FOR QUESTION02 ------------------
         public static void main(String[] args){
              new Keyboard2();
              A1Q2 p = new A1Q2();
              p.start();
    import java.util.*;
    public class Keyboard2 {     
         private static Scanner in = new Scanner(System.in);
         private static boolean useIndirection;
         public Keyboard2() {
              try {
                   useIndirection = (System.in).available() != 0;
              } catch(Exception e){}
         public static String readInput() {
              try {
                   if (useIndirection) {
                        String input = in.nextLine();
                        System.out.println(input);
                        return input;     
                   } else {
                        String input = in.nextLine();
                        return input;     
              } catch (IllegalStateException e) {
                   System.err.println("An error has occurred in the Keyboard.readInput() method.");
                   e.printStackTrace();
                   System.exit(-1);
              return null;
    }

    Snowboarder wrote:
    Hi everyone I'm trying run my program in NetBeans and i have two classes main one A1Q2 and Keyboard2. In main class NetBeans is seing that can not find Keyboard2 class . So everywhere where is Keyboard2 compiler highlited this for red color - red line. I can not figure out what is wrong. Please for any help . Apropos i've been using NetBeans from yeasterday.Huhh.. Well I am a big advocate of using tools that do not get in the way of development, and this sounds like a classic case where that applies*.
    The posted code compiles and runs just fine here (or seems to, as well as I understand its purpose) in a very simple editor I use to compile and run classes. Here is some example input/output..
        TEST 1.  An exception occurs when the user
        enters a String with more than 2 characters.
    Enter a String with less than 3 characters: 12
    Statement B
        TEST 2.  An exception occurs when the user
        enters a number < 0 or > 4
    Enter a number which is between 0 and 4 (inclusive): 1256
    CAUGHTjava.lang.ArrayIndexOutOfBoundsException: :1256
        TEST 3A.  An exception occurs when the user
        enters the number 7.
    Enter any number except 7: 5
    Enter a String of digits:* NetBeans is a powerful but complicated tool. When something goes wrong, it is much harder to figure out whether it is the code, or the IDE settings.
    For that basic reason, I would strongly recommend that people who are new to Java development use either..
    a) command line tools to do the job of compiling and running, or..
    b) write an ant script that can be run from the command line, or imported into most IDEs.
    As an aside, since both classes are in the default package (i.e. no package statement) they need to reside in the same directory to successfully compile and run. The default package is generally for toy and test classes, and there might be some quirks to using them. I mention that because I am wondering if somehow NetBeans has 'decided' to force people not to make classes in the default package.

Maybe you are looking for

  • How to find out the users currently logged into ODI

    Hi all, How to find out the users currently logged into ODI Work Repository? Thanks.

  • Cannot ping for either from host to guest nor from guest to host

    Hi I have installed virtual box 4.1.20 r80170 my host os is centos 6.3 64 bit my guest os is oracle linux 5.8 64 bit I've using bridge adapter for the network settings, but I'm neither able to ping from host to guest from guest to host may I know wha

  • Oracle ADF & Jdeveloper.

    Any one have an idea that which institute other than oracle school, give training for Oracle ADF & Jdeveloper in Dubai, United ARab Emirates. I am using Forms10g and would like to upgrade to Jdeveloper.I have no experience in Java.

  • Javascript Typewriter Tool in Acrobat

    Hi All, I am about to embark on a project for Batch Processing using Javascript, I am an extreme novice and do not know whether I am going down the right path. Does anyone know if the Typewriter tool can used via Javascript on Batch level, and what S

  • Imovie is not generating thumbnails for MPG video files

    Hi everyone, I have what I hope is a quick question with an easy solution.  I'm using iMovie '09 8.0.6 to make a movie for my parents of their granddaughter.  Imovie has generated thumbnails for all my video in iPhoto (most of which is .mov format),